<?php
class OrderApp extends MemberbaseApp {
    var $_order_mod;
    var $_atttype;
    var $_role;
    var $_user;
	public $countBox=0;
    function  __construct() {
        $this->OrderApp();
    }
    function OrderApp() {
        parent::__construct();
        $this->_order_mod=&m('order');
        Lang::load(lang_file('sourcing_task'));
        $atttype=array(
                'pigai'=>BELONGS_PIGAI,
                'zhidan'=>BELONGS_ZHIDAN,
                'hetong'=>BELONGS_HETONG,
                'chahuo'=>BELONGS_CHAHUO,
                'zhidan'=>BELONGS_ZHIDAN,
                'koukuan'=>BELONGS_KOUKUAN,
                'caigou'=>BELONGS_CAIGOU,
				'qcreport'=>BELONGS_ORDER_QC_REPORT
        );
        $perpage=$_GET['size']?intval($_GET['size']):20;
        define(PERPAGE, $perpage);
        $role = $this->visitor->get('role');
        $this->_role=$role;
        $user=$this->visitor->get();
        $this->user=$user;
        $this->assign('user',$user);
        $this->assign('role',$role);
        $now_date=date('Y-m-d',TIME);
        $this->assign('now_date',$now_date);
        $this->_atttype=$atttype;
        $this->assign('atttype',$atttype);
    }
    
    function index() {
        $this->_ican('view_order_list');
        $page=$_GET['page']?intval($_GET['page']):'1';
        $perpage=PERPAGE;
        $start=($page-1)*$perpage;
        $start<0 && $start=0;
	   $this->_curlocal("未确认订单");
	   $user = $this->visitor->get();
		
        $condition=$this->_get_conditions();
		
		//显示已确认前的所有订单
// 		if ($user['role']!=USER_CLIENT){
			$status_str="status in(".ORDER_STATUS_NO_CONFIRM.",".ORDER_STATUS_APPROVE.",".ORDER_STATUS_APPROVE_MANAGER.",".ORDER_STATUS_APPROVE_FINANCE.",".ORDER_STATUS_FACTORY_CONFIRM.")";
			
			$condition.=!empty($condition)?" AND {$status_str}":$status_str;
// 		}
		
		$this->assign("user",$user);
		
		if ($user['role'] == USER_MERCHANDISER_ADMIN) {
		//	$this->assign('user_manage', USER_MANAGER);
		//	$merch_id = empty($_GET['merch_id']) ? 0 : intval($_GET['merch_id']);
		//	if ($merch_id) {
		//		$conditions[] = "merchandiser_id = $merch_id";
		//	}
		    $mod_company_manager=&m("company_manager");
			$brand_mod =& m('brand');
			$conditions[]="o.brand_id in(select brand_id from {$brand_mod->table} where company_id in(select company_id from {$mod_company_manager->table} where uid={$this->visitor->get('user_id')}))";

		} elseif ($user['role'] == USER_ASSISTANT) {
			$merch_id = empty($_GET['merch_id']) ? 0 : intval($_GET['merch_id']);
			$this->assign('user_assistant', USER_ASSISTANT);
			$merch_ids = $user['user_id'];
			if ($merch_id) {
				$conditions[] = "merchandiser_id = $merch_id";
			} else {
				$conditions[] = "merchandiser_id in ($merch_ids)";
			}
		} elseif ($user['role'] == USER_FACTORY) {
			if (!$user['factory_id']){
				$this->show_warning('没有该工厂,如有疑问,请联系管理员');
				return;
			}
			$conditions[] = "factory_id = {$this->visitor->get('factory_id')}";
		}elseif ($user['role'] == USER_QC){
			$conditions[]  = $this->qc_factory_info($user);
		}elseif ($user['role']==USER_CLIENT){
// 			$status_str="status in(".ORDER_STATUS_NO_CONFIRM.",".ORDER_STATUS_FACTORY_CONFIRM.")";
// 			$condition.=!empty($condition)?" AND {$status_str}":$status_str;
			$merch_id = $user['user_id'];
			$conditions[] = "buyer_id = $merch_id";
		}elseif ($user['role']==USER_OUTGOING){
			//$conditions[]="1=1";
			$conditions[] = $this->qc_factory_info();
		}elseif ($user['role']==USER_MANAGER){
			$conditions[]="1=1";
		}
		else {
			$merch_id = $user['user_id'];
			$conditions[] = "merchandiser_id = $merch_id";
		}
		$conditions = ($condition ? ' AND ' : '') . implode(' AND ', $conditions);

		$condition .=$conditions;
        $page = $this->_get_page();
		$order = empty($_GET['order']) ? 'add_time DESC' : str_replace('-', ' ', trim($_GET['order']));
		if ($order != 'order_create_date DESC' || $order != 'order_create_date ASC') {
			$order .= ', add_time DESC';
		}
        $orders=$this->_order_mod->find(
                array(
                //'limit'=>"$start,$perpage",
                'conditions'=>$condition,
                    'count' => true,
                    'limit' => $page['limit'],
					'order' => $order.',style_sn desc'
                )
        );
        //$sql = "SELECT COUNT(*) FROM {$this->_order_mod->table}  " . ($condition?" where ".$condition:'');
        //$total_count = $this->_order_mod->getOne($sql);
        $page['item_count'] = $this->_order_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);
        //$this->_assign_order_dedial_info();
        // foreach($orders as $k=>$v) {
        //$orders[$k]=$this->_format_order($v);
        // }
		
        $this->_assign_common_info();
        if($_GET['search'] || $_GET['status'] =='1') {
            $this->assign('search', '1');
            $this->assign('get_para', ecm_json_encode($_GET));
        }
        $buyer_mod=&m('member');
        if ($this->_role==USER_CLIENT){
        	$buyers=$buyer_mod->find(array('conditions'=>'user_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }elseif ($this->_role==USER_MERCHANDISER){
        	$buyers=$buyer_mod->find(array('conditions'=>'freight_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }else{
        	$buyers=$buyer_mod->find(array('conditions'=>'activation=1 and role='.USER_CLIENT));
        }
        $this->assign('buyer_list',$buyers);
        $this->assign('orders',$orders);
		if ($this->visitor->get('role') == USER_MANAGER) {
			$this->assign('manager', USER_MANAGER);
		}
        $this->display('order.index.html');
    }
    function add() {
        $this->_ican('add_order');
        if(!IS_POST) {
        	$user=$this->visitor->get();
        	$sample_mod =& m('sample');
        	if ($user['role']==USER_CLIENT){
        		$this->assign('u_client',USER_CLIENT);
        		//属于客户的品牌
        		$member_mod=&m('member');
        		$member_info=$member_mod->get_info($this->visitor->get('user_id'));
        		$brand_mod=&m('brand');
        		$brands=$brand_mod->find(array(
        				'join'		=>'belong_company',
        				'conditions'=>'brand_id'.db_create_in($member_info['brand_arr_id'])
        		));
        		$this->assign('brand_list',$brands);
        			
        		//目的地
        		$brand_addr_name = $brand_mod->get(array('fields'=>'brand_addr','conditions'=>'brand_id'.db_create_in($member_info['brand_arr_id'])));
        		$brand_addr_list = explode(",",$brand_addr_name['brand_addr']);
        		$this->assign("brand_addr_name",$brand_addr_list);
        		
        		//买手
        		$buyer_list=$member_mod->find(array(
        				'conditions'=>'user_id='.$this->visitor->get('user_id').' and role='.USER_CLIENT
        		));
        		$this->assign('buyer_list',$buyer_list);
        		
        		//跟单
        		if ($member_info['freight_id']){
        			$merchandiser_list=$member_mod->find(array(
        					'conditions'=>'user_id='.$member_info['freight_id'].' and role='.USER_MERCHANDISER
        			));
        		}
        		$this->assign('merchandiser_list',$merchandiser_list);
        		
        		$factory_mod =& m('factory_info');
        		$factory_list=$factory_mod->find(array('conditions'=>'factory_id='.DEFAULT_FACTORY_ID,'order'=>'factory_name'));
        		$this->assign('factory_list', array_filter($factory_list));
        		
        		$this->assign('sample_list', $sample_mod->find(array('order'=>'sample_sn ASC','conditions'=>'buyer_id='.$user['user_id'])));
        		$style_mod =& m('style');
        		$this->assign('style_list', $style_mod->find(array('conditions'=>'if_show=1','order'=>'style_name DESC')));
        		$style_sn_list = $this->_order_mod->getall("select style_sn from {$this->_order_mod->table} where buyer_id={$user['user_id']} and (style_sn!='') group by style_sn");
        		$this->assign('style_sn_list', $style_sn_list);
        	}else{
        		$this->_assign_common_info();
        		$this->_assign_order_dedial_info();
        		$this->assign('merchandiser_list',array($user));
        		
        		$this->assign('sample_list', $sample_mod->find(array('order'=>'sample_sn ASC')));
        		$style_mod =& m('style');
        		$this->assign('style_list', $style_mod->find(array('conditions'=>'if_show=1','order'=>'style_name DESC')));
        		$style_sn_list = $this->_order_mod->getall("select style_sn from {$this->_order_mod->table} where style_sn!='' group by style_sn");
        		$this->assign('style_sn_list', $style_sn_list);
        	}
        	
//         	$file_mod =& m('upload');
//         	$file_comment=$file_mod->find(array(
//         			'conditions' => 'file_type = ' . BELONGS_CONSUMER_COMMENT_ORDER . ' AND key_id = ' . DEFAULT_CUSTOMER_KEY_ID.' and session_id="'.session_id().'"',
//         			'order' => 'file_id ASC',
//         	));
//         	$file_remarks=$file_mod->find(array(
//         			'conditions' => 'file_type = ' . BELONGS_CONSUMER_REMARKS_ORDER . ' AND key_id = ' . DEFAULT_CUSTOMER_KEY_ID.' and session_id="'.session_id().'"',
//         			'order' => 'file_id ASC',
//         	));
        	$this->assign('file_comment',$file_comment);
        	$this->assign('file_remarks',$file_remarks);
        	
            //客户评语跟备注
            $this->assign('consumer_comment_order',BELONGS_CONSUMER_COMMENT_ORDER);
            $this->assign('consumer_remarks_order',BELONGS_CONSUMER_REMARKS_ORDER);
            $this->assign('default_cust_id',DEFAULT_CUSTOMER_KEY_ID);
			$this->_curlocal("创建新订单");
            $this->display('order.html');
        }
        else {
			$submit_val=isset($_POST['submit'])?trim($_POST['submit']):"";
			$clone_order_id=isset($_POST['clone_order_id'])?intval($_POST['clone_order_id']):0;
			$file_mod =& m('upload');
			$ss_mod =& m('ss');
			$cq_mod =& m('cq');
			$size_ss_mod =& m('size_ss');
			$fabric_info_mod =& m('fabric_info');
			
			  if($this->user['is_factory']==1)
			  {
			  $this->show_warning('工厂用户无法新增订单');
			  return;
			  }
			  $data=$this->_handle_post_info($_POST['info']);
			  if($data['merchandiser_id'] !=$this->user['user_id'] and $this->_role==USER_MERCHANDISER){
				  //$this->show_warning('您不能使用此跟单');
				  //return;
			  }
  
			  
			  $data["add_time"]=gmtime();
			  $id=$this->_order_mod->add($data);
			  
			  //复制翻单的批改和制单数据
			  if($submit_val=="翻单")
			  {
			  	$pigai_list=$file_mod->find(array('conditions'=>'file_type ='.BELONGS_PIGAI.' AND key_id = '.$clone_order_id,'order' => 'file_id ASC',));
			   	 foreach($pigai_list as $key=>$item)
				 {
					 unset($pigai_list[$key]['file_id']);
					 $pigai_list[$key]['key_id']=$id;
					 $file_mod->add($pigai_list[$key]);

				 }
				 if ($clone_order_id){
				 	$clone_order=$this->_order_mod->get($clone_order_id);
				 	$this->_order_mod->edit($id,array('parent_id'=>$clone_order_id,'production_board'=>$clone_order['production_board'],'large_cargo_cloth'=>$clone_order['large_cargo_cloth'],'bow_board'=>$clone_order['bow_board']));
				 }
				 $ss_info=$ss_mod->get("order_id={$clone_order_id}");
				 if(!empty($ss_info))
				 {
					 $ss_id=$ss_info['ss_id'];
					 $ss_info['ss_status']=SS_STATUS_CREATE;
					 $ss_info['order_id']=$id;
					 unset($ss_info['ss_id']);
					 $new_ss_id=$ss_mod->add($ss_info);
				 
				 	//增加制单颜色数量信息
					$cq_list=$cq_mod->find(array('conditions'=>"ss_id={$ss_id}"));
				   if(!empty($cq_list))
				   {
					   foreach($cq_list as $key=>$item)
					   {
					    $cq_list[$key]['ss_id']=$new_ss_id;
					    unset($cq_list[$key]['cq_id']);
						$cq_mod->add($cq_list[$key]);
					   }
						
				   }
				   //增加制单尺寸信息
					$size_ss_list=$size_ss_mod->find(array('conditions'=>"ss_id={$ss_id}"));
				   if(!empty($size_ss_list))
				   {
					   foreach($size_ss_list as $key=>$item)
					   {
					    $size_ss_list[$key]['ss_id']=$new_ss_id;
					    unset($size_ss_list[$key]['size_ss_id']);
						$size_ss_mod->add($size_ss_list[$key]);
					   }
						
				   }
				   //增加制单面料信息
					$fabric_list=$fabric_info_mod->find(array('conditions'=>"ss_id={$ss_id}"));
				   if(!empty($fabric_list))
				   {
					   foreach($fabric_list as $key=>$item)
					   {
					    $fabric_list[$key]['ss_id']=$new_ss_id;
					    unset($fabric_list[$key]['fabric_info_id']);							
						$fabric_info_mod->add($fabric_list[$key]);
					   }
				   }
				 
			     }
	
			  }
			  $this->_send_mail_on_create($this->_order_mod->get($id));
			  //处理上传的客人评语
			  $consumer_comment=$file_mod->find(array('conditions'=>'file_type ='.BELONGS_CONSUMER_COMMENT_ORDER.' AND key_id = '.$clone_order_id,'order' => 'file_id ASC',));
			  foreach($consumer_comment as $k=>$v)
			  {
			  	unset($consumer_comment[$k]['file_id']);
			  	$consumer_comment[$k]['key_id']=$id;
			  	$file_mod->add($consumer_comment[$k]);
			  }
        		$consumer_remark=$file_mod->find(array('conditions'=>'file_type ='.BELONGS_CONSUMER_REMARKS_ORDER.' AND key_id = '.$clone_order_id,'order' => 'file_id ASC',));
			  foreach($consumer_remark as $j=>$val)
			  {
			  	unset($consumer_remark[$j]['file_id']);
			  	$consumer_remark[$j]['key_id']=$id;
			  	$file_mod->add($consumer_remark[$j]);
			  }
			  if($data['sample_id']) {
				  $sample_mode=&m('sample');
				  $sample_mode->edit($data['sample_id'],array('order_id'=>$id,'is_order'=>'1','order_sn'=>$data['order_sn'],'order_create_date'=>strtotime($data['order_create_date'])));
			  }
			  if($id) {
				  IS_AJAX?$this->msg_ok($data, '添加成功'):$this->show_message('添加成功','新建订单','index.php?app=order');
			  }
			  else {
				  IS_AJAX?$this->msg_ok($data,$this->_order_mod->get_error()):$this->show_message($this->_order_mod->get_error());
			  }
        }
    }
    function edit() {
        //$this->_ican('order_status');
        $id=$_GET['id']?intval($_GET['id']):0;
        $user_info=$this->visitor->get();
        $file_mod=&m('upload');
        if(!$id) {
            $this->show_warning('请选择订单');
			return;
        }
		/* //质检编辑质检报告文本
		if(IS_POST && $this->visitor->get("role")==USER_QC)
		{
			$qcreport_text=isset($_POST['info']['qcreport_text'])?trim($_POST['info']['qcreport_text']):"";
			$this->_order_mod->edit($id,array('qcreport_text'=>$qcreport_text) );
			if ($this->_order_mod->get_error()) {
				$this->show_warning($this->_order_mod->get_error());
				return;
			}
		} */
		
        $order=$this->_order_mod->get($id);
        if(!$order) {
            $this->show_warning('订单不存在');
			return;
        }
//         $quote_mod=& m('quote');
//         $page = $this->_get_page(10);
//         	//获取加工工厂的报价信息
//         	if (in_array($user_info['role'], array(USER_MANAGER,USER_MERCHANDISER,USER_FINANCE,USER_MERCHANDISER_ADMIN))){
//         		$quote_list=$quote_mod->find(array(
//         				'join'=>'belongs_factory',
//         				'conditions'=>'order_id='.$id,
//         				'count'=>true,
//         				'limit'=>$page['limit']
//         		));
//         		if (!empty($quote_list)){
//         			foreach ($quote_list as $key=>$rows){
//         				$f_id=$rows['factory_id'];
//         				$quote_list[$key]['order_num']=$quote_mod->getOne("select sum(order_num) from {$quote_mod->table} where if_option=1 and factory_id=".$f_id);
//         				$quote_list[$key]['file_quote']=$file_mod->find(array('conditions'=>'file_type = '.BELONGS_QUOTE_ORDER.' AND key_id = '.$rows['quote_id'],'order'=>'file_id ASC'));
//         			}
//         		}
//         		$page['item_count'] = $quote_mod->getCount();
//         		/* 报价附件 */
//         		$this->assign('belongs_quote_order', BELONGS_QUOTE_ORDER);
//         		$this->assign('quote_list',$quote_list);
//         }

		if($this->visitor->get("role")==USER_FACTORY)
		{
			header("location:index.php?app=order&act=view&id={$id}");
			return;
		}
		
		if($this->visitor->get("role")==USER_FACTORY&&$order['factory_id']!=$this->visitor->get("factory_id"))
		{
			$this->show_warning('用户无权限操作此订单');
			return;
		}
		
		
		//限制那些状态只能哪些角色编辑
		$is_edit=$this->_check_order_is_edit($order);
		$this->assign("is_edit",$is_edit);
		
		//添加一个限制条件  
		$factory_role=$this->visitor->get('role');
		if(in_array($factory_role, array(USER_FACTORY)) and $order['status'] == ORDER_STATUS_FACTORY_CONFIRM){
			$this->assign('factory_role',true);
		}elseif ($factory_role==USER_QC){
			$this->assign('qc_role',true);
		}

		$this->assign('user', $user_info);
		
		//获取对应的制单信息
		$ss_mod =& m('ss');
		$ss_info=$ss_mod->get("order_id={$id}");
		$this->assign("ss_info",$ss_info);
		
		//显示裁床颜色信息
// 		if (!empty($ss_info)){
// 			$cq_mod=& m('cq');
// 			$cut_list=$cq_mod->find(array(
// 					'conditions'=>'ss_id='.$ss_info['ss_id'],
// 					'fields'=>'color,cq_id'
// 			));
// 			$this->assign('cut_list',$cut_list);
// 		}
		
		//显示裁床信息
// 		$cut_bed_mod=&m('cut_bed');
// 		$cut_bed=$cut_bed_mod->find(array(
// 			'conditions'=>'order_id='.$id,
// 			'order'=>'cb_id desc'	
// 		));
// 		$this->assign('cut_bed',$cut_bed);
		
		//显示qc查货进度列表
		$process_mod=& m('qc_process');
		$process_list=$process_mod->find(array(
			'conditions'=>'order_id='.$id,
			'order'=>'receipt_time desc'	
		));
		if (!empty($process_list)){
			$member_mod=&m('member');
			foreach ($process_list as $k=>$val){
				$qc_id=$val['qc_id'];
				$mem_info=$member_mod->get($qc_id);
				$process_list[$k]['qc_name']=$mem_info['user_name'];
			}
		}
		$this->assign('process_list',$process_list);
		
		//如果存在大货单信息就显示
		/* $fabric_info_mod =& m('fabric_info');
		$fabric_info_list = $fabric_info_mod->find(array(
				'conditions'=>'order_id='.$id,
				'fields'=>"fabric_info.fabric_info_id,sample_id,fabric_info.description,fabric_info.fabric_shop_id,item,price,width,picture,fabric_shop_name,colors,fabric_num,phone_mob,address,cc_id,fabric_characteristics,fabric_info.bulk_id,fabric_info.bulk_status",
				'join'	=>"belongs_fabric_shop",
				'order'=>'fabric_info_id ASC'
		));
		$fabric_order_mod =& m('fabric_order');
		$sour_mod =& m('sourcing_info');
		$sour_list=$sour_mod->get(array(
			'conditions'=>'order_id='.$id,
			'order'=>'add_time desc',
			'fields'=>'sourcing_id'
		));
		if ($order['sample_id']){
			$sample_list=$sour_mod->get(array(
					'conditions'=>'sample_id='.$order['sample_id'],
					'fields'=>'sample_id'
			));
		} */
		//如果不存在大货单就显示最新生产板或者头板的信息
		/* if (empty($fabric_info_list)){
			if (!empty($sour_list)){
				$fabric_info_list=$fabric_order_mod->find(array(
						'conditions'=>'order_id='.$id.' and sourcing_id='.$sour_list['sourcing_id'],
						'fields'=>"fabric_order.fabric_info_id,fabric_order.description,fabric_order.fabric_shop_id,item,price,fabric_shop_name,colors,fabric_num,phone_mob,address,cc_id,fabric_characteristics",
						'join'	=>"belongs_fabric_shop",
						'order'=>'fabric_info_id ASC'
				));
				if (empty($fabric_info_list)){
					if (!empty($sample_list)){
						$fabric_info_list=$fabric_info_mod->find(array(
								'conditions'=>'sample_id='.$sample_list['sample_id'],
								'fields'=>"fabric_info.fabric_info_id,fabric_info.description,fabric_info.fabric_shop_id,item,price,fabric_shop_name,colors,fabric_num,phone_mob,address,cc_id,fabric_characteristics",
								'join'	=>"belongs_fabric_shop",
								'order'=>'fabric_info_id ASC'
						));
					}
				}
				if (!empty($fabric_info_list)){
					foreach ($fabric_status_list as $keys=>$res){
						$fabric_info_list[$keys]['fabric_info_id']=0;
					}
				}
			}else{
				if (!empty($sample_list)){
					$fabric_info_list=$fabric_info_mod->find(array(
							'conditions'=>'sample_id='.$sample_list['sample_id'],
							'fields'=>"fabric_info.fabric_info_id,fabric_info.description,fabric_info.fabric_shop_id,item,price,fabric_shop_name,colors,fabric_num,phone_mob,address,cc_id,fabric_characteristics",
							'join'	=>"belongs_fabric_shop",
							'order'=>'fabric_info_id ASC'
					));
					if (!empty($fabric_info_list)){
						foreach ($fabric_info_list as $keys=>$res){
							$fabric_info_list[$keys]['fabric_info_id']=0;
						}
					}
				}
			}
		}
		$this->assign('fabric_info_list', $fabric_info_list);
		 */
		/* if (in_array($user_info['role'], array(USER_MANAGER,USER_QC,USER_FINANCE,USER_OUTGOING))){
			$receipt_mod=&m('receipt');
			$receipt_list=$receipt_mod->find(array(
					'join'=>'belongs_factory',
					'conditions'=>'order_id='.$id
			));
			$file_mod=&m('upload');
			if (!empty($receipt_list)){
				foreach ($receipt_list as $key=>$res){
					$receipt_list[$key]['file_receipt']=$file_mod->find(array(
							'conditions' => 'file_type = ' . BELONGS_RECEIPT_ORDER . ' AND key_id = ' . $res['receipt_id'],
							'order' => 'file_id ASC',
					));
				}
			}
			$this->assign('receipt_list',$receipt_list);
		} */
		
		$sample_mod =& m('sample');
		$user_mod =& m('member');
		//qc列表
// 		if (in_array($user_info['role'], array(USER_QC,USER_OUTGOING))){
// 			$qc_list=$user_mod->find(array(
// 					'conditions'=>'if_show=1 and role='.USER_QC,
// 					'order'=>'user_name asc'
// 			));
// 			$this->assign('qc_list',$qc_list);
// 			$qc_factory_mod=&m('qcfactory');
// 			$qf=$qc_factory_mod->get("order_id=".$id);
// 			if (!empty($qf)){
// 				$this->assign('qf',$qf['user_id']);
// 			}
// 		}
			
		if (!IS_POST || !$is_edit) {
			//赋值进度记录
			$mod_pro_records=&m("pro_records");
			$pro_records_list=$mod_pro_records->find(array(
				'conditions'=>"key_id={$id} AND type=".PRO_RECORDS_ORDER,
				'order'	=>"rec_time desc"
			));
			$this->assign("pro_records_list",$pro_records_list);
			
			//赋值色卡信息
			$colorcard_mode=& m('color_card');
			
			$fabric_shop_list=$colorcard_mode->getall("select fabric_shop_name,fabric_shop_id from {$colorcard_mode->table} group by fabric_shop_id order by fabric_shop_name,update_time desc");

			$this->assign("fabric_shop_list",$fabric_shop_list);
			
			$brand_mod =& m('brand');
			$this->assign('brand_list',$brand_mod->find(array('conditions'=>'if_show=1','order'=>'brand_name ASC','join'=>"belong_company",)));
			$brand_addr_name = $brand_mod->get(array('fields'=>'brand_addr','conditions'=>'brand_id='.$order[brand_id]));
			$brand_addr_list = explode(",",$brand_addr_name['brand_addr']);
			$this->assign("brand_addr_name",$brand_addr_list);
			$brand_info=$brand_mod->get($order['brand_id']);
			$company_id=!empty($brand_info)?$brand_info['company_id']:0;
			
// 			if ($order['brand_id']){
// 				$this->_assign_main_label($order['brand_id']);
// 				$this->_assign_listing($order['brand_id']);
// 			}
			
			$buyer_mod =& m('member');
			$this->assign('buyer_list', $buyer_mod->find(array(
					'conditions' => 'activation=1 and if_show = 1 and role='.USER_CLIENT,
					'order' => 'user_name asc'
			)));
			
			$this->assign('merchandiser_list', $user_mod->find(array('conditions'=>'if_show=1 AND role='.USER_MERCHANDISER.' AND user_id='.$order['merchandiser_id'])));
			
			$this->assign('sample_list', $sample_mod->find(array('order'=>'sample_sn ASC')));
			
			$style_mod =& m('style');
			$this->assign('style_list', $style_mod->find(array('conditions'=>'if_show=1','order'=>'style_name DESC')));
			
			$factory_mod =& m('factory_info');
			$this->assign('factory_list', $factory_mod->find(array('join'=>'belongs_factory_member','conditions'=>'if_show=1 and activation=1','order'=>'factory_name DESC')));
			
			$fs_mod =& m('fabric_shop');
			$this->assign('fabricshop_list', $fs_mod->find(array('conditions'=>'if_show=1','order'=>'fabric_shop_name ASC')));
			
			/* //分批收货能添加的工厂
			$goods_info=$quote_mod->find(array(
				'conditions'=>'if_option=1 and order_id='.$id,
				'fields'=>'factory_id'	
			));
			if (!empty($goods_info)){
				foreach ($goods_info as $goods){
					$fact_id[]=$goods['factory_id'];
				}
				$t_id=implode(',', $fact_id);
				if ($t_id){
					$this->assign('f_list',$factory_mod->find(array('join'=>'belongs_factory_member','conditions'=>'if_show=1 and factory_info.factory_id'.db_create_in($t_id),'order'=>'factory_name DESC')));
				}
			} */
			if (!empty($order)){
				$order['contract_file']=$file_mod->find(array(
					'conditions'=>'key_id='.$id.' and file_type='.BELONGS_QUOTE_CONTRACT,
					'fields'=>'file_id,file_name'	
				));
				$order['cut_file']=$file_mod->find(array(
					'conditions'=>'key_id='.$id.' and file_type='.BELONGS_CUT_ORDER,
					'fields'=>'file_id,file_name'	
				));
				$order['statement_list']=$file_mod->find(array(
						'conditions'=>'key_id='.$id.' and file_type='.BELONGS_STATEMENT_FILE,
						'fields'=>'file_id,file_name'
				));
				
// 				//细节图
// 				$order['consumer_order_thumb'] = $file_mod->find(array(
// 						'conditions' => 'file_type = ' . BELONGS_ORDER_THUMB_IMG . ' AND key_id = ' . $id,
// 						'order' => 'file_id ASC',
// 				));
			}
			$this->_assign_files($order['order_id'], $order['sample_id']);
			$this->_format_page($page);
			$this->assign('page_info', $page);
			$this->assign('belongs_receipt_order',BELONGS_RECEIPT_ORDER);
			$this->assign('default_cust_id',DEFAULT_CUSTOMER_KEY_ID);
			$this->assign('belongs_quote_contract',BELONGS_QUOTE_CONTRACT);
			$this->assign('belongs_cut_order',BELONGS_CUT_ORDER);
			$this->assign('belongs_process_receipt',BELONGS_PROCESS_RECEIPT);
// 			$this->assign('belongs_order_thumb',BELONGS_ORDER_THUMB_IMG);
			$this->assign('quote_list',$quote_list);
			$this->assign('order', $order);
			$this->assign('role', $this->visitor->get('role'));
			$this->assign('page_title', '订单信息');
            $this->display('order.form2.html');
		} else {
			$submit_val= trim($_POST['submit']);
			
			$data=$this->_handle_order_status($_POST['info']);
			$data['brand_addr'] =isset($_POST['info']['brand_addr'])?$_POST['info']['brand_addr']:'';
			 
			$approve_no_desc=isset($_POST['approve_no_desc'])?trim($_POST['approve_no_desc']):"";
			if($order['status']==ORDER_STATUS_NO_CONFIRM)
			{
				$brand_id=isset($_POST['info']['brand_id'])?intval($_POST['info']['brand_id']):0;
				$buyer_id=isset($_POST['info']['buyer_id'])?intval($_POST['info']['buyer_id']):0;
				$merchandiser_id=isset($_POST['info']['merchandiser_id'])?intval($_POST['info']['merchandiser_id']):0;
				$style_id=isset($_POST['info']['style_id'])?intval($_POST['info']['style_id']):0;
		
				$brand_mod =& m('brand');
				$brand_info= $brand_mod->get($brand_id);
				
				$buyer_mod =& m('member');
				$buyer_info= $buyer_mod->get($buyer_id);
				
				$user_mod =& m('member');
				$merchandiser_info=$user_mod->get($merchandiser_id);
				$style_mod =& m('style');
				$style_info= $style_mod->get($style_id);
				$sample_id=isset($_POST['info']['sample_id'])?intval($_POST['info']['sample_id']):0;
				$sample_info=$sample_mod->get($sample_id);
				if (empty($brand_info)) {
					$this->show_warning('请选择品牌');
					exit();
				}
				if (empty($buyer_info)) {
					$this->show_warning('请选择买手');
					exit();
				}
				if (empty($merchandiser_info)) {
					$this->show_warning('请选择跟单');
					exit();
				}
				if (empty($style_info)) {
					$this->show_warning('请选择款式');
					exit();
				}
				$data['brand_name']=$brand_info['brand_name'];
				$data['buyer_name']=$buyer_info['user_name'];
				$data['merchandiser']=$merchandiser_info['user_name'];
				$data['style_name']=$style_info['style_name'];
				$data['sample_sn']=$sample_info['sample_sn'];
				if ($user_info['role']==USER_CIVILIAN){
					$data['is_keep_sample']=trim($_POST['is_keep_sample']);
				}
			}
			
			$m_id=isset($_POST['main_label'])?intval($_POST['main_label']):0;
			$list_id=isset($_POST['listing_code'])?intval($_POST['listing_code']):0;
			$mod_pro_records=&m("pro_records");
			$log_time=gmtime();
			$work_amount=isset($_POST['info']['work_amount'])?floatval($_POST['info']['work_amount']):0;
			switch($order['status'])
			{
				case ORDER_STATUS_NO_CONFIRM:		//未确认
				  if($submit_val=="送主管审批")
				  {
					  $data['status'] = ORDER_STATUS_APPROVE;
					  $pro_data=array(
							  "type"=>PRO_RECORDS_ORDER,
							  "key_id"=>$id,
							  "rec_name"=>$this->visitor->get("user_name"),
							  "rec_buff"=>"送主管审批",
							  "rec_time"=>$log_time			
						  );
						if(!$mod_pro_records->add($pro_data))
						{
						   $this->show_warning($mod_pro_records->get_error());
						}
				  }
				break;
				case ORDER_STATUS_APPROVE:		//待审批
				  if ($submit_val=="审批通过") {
					  	if(in_array($this->visitor->get("role"), array(USER_MANAGER,USER_MERCHANDISER_ADMIN)))
						{
						  $data['status'] = ORDER_STATUS_APPROVE_FINANCE;
						}
						elseif($this->visitor->get("role")==USER_FINANCE)
						{
						  $data['status'] = ORDER_STATUS_APPROVE_MANAGER;
	
						}
					}
					elseif($submit_val=="审批不通过")
					{
						$data['status'] = ORDER_STATUS_NO_CONFIRM;
						if (empty($approve_no_desc)) {
							  $this->show_warning('请输入审批不通过理由');
							  return;
						  }
					}
				break;
				case ORDER_STATUS_APPROVE_MANAGER:		//主管审批
				if(in_array($this->visitor->get("role"), array(USER_MANAGER,USER_MERCHANDISER_ADMIN)))
				{
				  if ($submit_val=="审批通过") {
						  $data['status'] = ORDER_STATUS_FACTORY_CONFIRM;
					}
				  elseif($submit_val=="审批不通过")
					{
						if (empty($approve_no_desc)) {
							  $this->show_warning('请输入审批不通过理由');
							  return;
						  }
						$data['status'] = ORDER_STATUS_NO_CONFIRM;
					}
				}
				break;
				case ORDER_STATUS_APPROVE_FINANCE:		//财务审批
				if($this->visitor->get("role")==USER_FINANCE)
				{
				  if ($submit_val=="审批通过") {
						  $data['status'] = ORDER_STATUS_FACTORY_CONFIRM;
					}
				  elseif($submit_val=="审批不通过")
					{
						if (empty($approve_no_desc)) {
							  $this->show_warning('请输入审批不通过理由');
							  return;
						  }
						$data['status'] = ORDER_STATUS_NO_CONFIRM;
					}
				}
				break;
				case ORDER_STATUS_FACTORY_CONFIRM:		//工厂确认
				  if ($submit_val=="确认订单") {
						  $data['status'] = ORDER_STATUS_CONFIRM;
						  $pro_data=array(
							  "type"=>PRO_RECORDS_ORDER,
							  "key_id"=>$id,
							  "rec_name"=>$this->visitor->get("user_name"),
							  "rec_buff"=>"工厂确认",
							  "rec_time"=>$log_time			
						  );
						if(!$mod_pro_records->add($pro_data))
						{
						   $this->show_warning($mod_pro_records->get_error());
						}
					}
				break;
				case ORDER_STATUS_NO_CANCEL:		//已取消
				  if ($this->visitor->get("role")!=USER_FACTORY) {
						  $data['status'] = ORDER_STATUS_NO_CONFIRM;
						  $pro_data=array(
							  "type"=>PRO_RECORDS_ORDER,
							  "key_id"=>$id,
							  "rec_name"=>$this->visitor->get("user_name"),
							  "rec_buff"=>"取消订单",
							  "rec_time"=>$log_time			
						  );
						if(!$mod_pro_records->add($pro_data))
						{
						   $this->show_warning($mod_pro_records->get_error());
						}
					}
				break;
			}
			
			if($submit_val=="重置" && in_array($this->visitor->get("role"), array(USER_MANAGER,USER_MERCHANDISER_ADMIN)))
			{
			  $data['status'] = ORDER_STATUS_NO_CONFIRM;
			  $pro_data=array(
					"type"=>PRO_RECORDS_ORDER,
					"key_id"=>$id,
					"rec_name"=>$this->visitor->get("user_name"),
					"rec_buff"=>"重置订单",
					"rec_time"=>$log_time			
				);
			  if(!$mod_pro_records->add($pro_data))
			  {
				 $this->show_warning($mod_pro_records->get_error());
			  }
			}
			
			if(($order['status']==ORDER_STATUS_APPROVE&&$data['status']==ORDER_STATUS_APPROVE_MANAGER) || ($order['status']==ORDER_STATUS_APPROVE_FINANCE&&$data['status']==ORDER_STATUS_FACTORY_CONFIRM))
			{

				$pro_data=array(
					"type"=>PRO_RECORDS_ORDER,
					"key_id"=>$id,
					"rec_name"=>$this->visitor->get("user_name"),
					"rec_buff"=>"财务审批通过",
					"rec_time"=>$log_time			
				);
			  if(!$mod_pro_records->add($pro_data))
			  {
				 $this->show_warning($mod_pro_records->get_error());
			  }

			}
			elseif(($order['status']==ORDER_STATUS_APPROVE&&$data['status']==ORDER_STATUS_APPROVE_FINANCE) || ($order['status']==ORDER_STATUS_APPROVE_MANAGER&&$data['status']==ORDER_STATUS_FACTORY_CONFIRM))
			{

				$pro_data=array(
					"type"=>PRO_RECORDS_ORDER,
					"key_id"=>$id,
					"rec_name"=>$this->visitor->get("user_name"),
					"rec_buff"=>"主管审批通过",
					"rec_time"=>$log_time			
				);
			  if(!$mod_pro_records->add($pro_data))
			  {
				 $this->show_warning($mod_pro_records->get_error());
			  }

			}
			elseif(in_array($order['status'],array(ORDER_STATUS_APPROVE_MANAGER,ORDER_STATUS_APPROVE,ORDER_STATUS_APPROVE_FINANCE))&&$data['status']==ORDER_STATUS_NO_CONFIRM)
			{
				if ($this->visitor->get('role')==USER_MANAGER){
					$rec_buff="主管";
				}elseif ($this->visitor->get('role')==USER_MERCHANDISER_ADMIN){
					$rec_buff="跟单主管";
				}else{
					$rec_buff="财务";
				}
				$rec_buff .="审批不通过,理由:{$approve_no_desc}";
				
				$pro_data=array(
					"type"=>PRO_RECORDS_ORDER,
					"key_id"=>$id,
					"rec_name"=>$this->visitor->get("user_name"),
					"rec_buff"=>$rec_buff,
					"rec_time"=>$log_time			
				);
			  if(!$mod_pro_records->add($pro_data))
			  {
				 $this->show_warning($mod_pro_records->get_error());
			  }
				
			}

			/* if (in_array($user_info['role'], array(USER_MANAGER,USER_QC,USER_FINANCE,USER_OUTGOING))){
				$data['ship_count']=trim($_POST['ship_count']);
				$data['fact_ship_num']=trim($_POST['fact_ship_num']);
				$data['finish_case']=trim($_POST['finish_case']);
				$data['score_case']=trim($_POST['score_case']);
			} */
			
			if($this->visitor->get("role")==USER_FINANCE && in_array($order['status'],array(ORDER_STATUS_APPROVE,ORDER_STATUS_APPROVE_FINANCE)))
			{
			  $data['work_amount'] = $work_amount;
			  $data['all_work_amount'] = floatval($order['ship_count'])*$work_amount;
			}
			$data['m_id']=$m_id;
			$data['list_id']=$list_id;
			$pigai=$file_mod->find(array('conditions'=>'file_type = '.BELONGS_HETONG.' AND key_id = '.$id,'order'=>'file_id ASC'));
			if (!empty($pigai)){
				$data['is_upload_tm']=1;
			}else{
				$data['is_upload_tm']=0;
			}
			
			//同步更新船头板、生产板等信息
			$sy_data=array();
			$sy_data['production_board']=isset($_POST['info']['production_board'])?$_POST['info']['production_board']:"";
			$sy_data['large_cargo_cloth']=isset($_POST['info']['large_cargo_cloth'])?$_POST['info']['large_cargo_cloth']:"";
			$sy_data['bow_board']=isset($_POST['info']['bow_board'])?$_POST['info']['bow_board']:"";
			if ($order['parent_id']){
				$order_arr=$this->_order_mod->find(array(
					'conditions'=>'(parent_id='.$order['parent_id'].' or order_id='.$order['parent_id'].') and status not '.db_create_in(array(ORDER_STATUS_SHIPPED,ORDER_STATUS_NO_CANCEL,ORDER_STATUS_PAY_MONEY)),' and merchandiser_id='.$order['merchandiser_id'],
					'fields'=>'order_id'	
				));
				if (!empty($order_arr)){
					foreach ($order_arr as $k=>$v){
						$oid=$v['order_id'];
						$this->_order_mod->edit($oid,$sy_data);
					}
				}
			}else{
				$order_arr=$this->_order_mod->find(array(
						'conditions'=>'parent_id='.$id.' and status not '.db_create_in(array(ORDER_STATUS_SHIPPED,ORDER_STATUS_NO_CANCEL,ORDER_STATUS_PAY_MONEY)),' and merchandiser_id='.$order['merchandiser_id'],
						'fields'=>'order_id'
				));
				if (!empty($order_arr)){
					foreach ($order_arr as $k=>$v){
						$oid=$v['order_id'];
						$this->_order_mod->edit($oid,$sy_data);
					}
				}
			}
			$this->_order_mod->edit($id,$data);
			if ($this->_order_mod->get_error()) {
				$this->show_warning($this->_order_mod->get_error());
				return;
			}
			//更改工厂的时候清除进度记录
			$factory_id=isset($data['factory_id'])?intval($data['factory_id']):0;
			if(!empty($factory_id))
			{
				if($factory_id!=$order['factory_id'])
				{
					$mod_pro_records->drop("type=".PRO_RECORDS_ORDER." AND key_id={$id}" );
				}
			}
			
			
			//裁床信息
// 			if (in_array($user_info['role'],array(USER_QC))){
// 				$new_cut_id=array();
// 				$colors=array_filter($_POST['colors']);
// 				if (!empty($colors)){
// 					foreach($_POST['colors'] as $key=>$items)
// 					{
// 						$cb_id=isset($_POST['cb_id'][$key])?intval($_POST['cb_id'][$key]):0;
// 						$cut_data=array(
// 								"order_id"=>$id,
// 								"colors"=>isset($_POST['colors'][$key])?trim($_POST['colors'][$key]):"",
// 								"color_desc"=>isset($_POST['color_desc'][$key])?trim($_POST['color_desc'][$key]):"",
// 								"order_num"=>isset($_POST['order_num'][$key])?intval($_POST['order_num'][$key]):"",
// 								"fact_num"=>isset($_POST['fact_num'][$key])?trim($_POST['fact_num'][$key]):"",
// 								"error_num"=>isset($_POST['error_num'][$key])?$_POST['error_num'][$key]:"",
// 						);
// 						if(!empty($cut_data['colors']) || !empty($cut_data['fact_num']))
// 						{
// 							if(empty($cb_id))
// 							{
// 								$cb_id=$cut_bed_mod->add($cut_data);
// 							}
// 							else
// 							{
// 								$new_cut_id[]=$cb_id;
					
// 								$cut_bed_mod->edit("cb_id={$cb_id}",$cut_data);
// 							}
// 						}
// 					}
// 				}
		
// 				if (!empty($cut_bed)){
// 					foreach($cut_bed as $cut_rows)
// 					{
// 						if(!in_array($cut_rows['cb_id'],$new_cut_id))
// 						{
// 							$cut_bed_mod->drop("cb_id={$cut_rows['cb_id']}");
// 						}
// 					}
// 				}
// 			}
			
			//当送审批等状态发送对应的邮件
			$new_order=$this->_order_mod->get($id);
			if($order['status']==ORDER_STATUS_NO_CONFIRM&&$new_order['status']==ORDER_STATUS_APPROVE)  //送主管审批时发送邮件
			{
				$this->_send_mail_on_send_approve($new_order);
				header("location:index.php?app=order&act=view&id={$id}");
				return;
			}
			elseif($order['status']==ORDER_STATUS_APPROVE&&$new_order['status']==ORDER_STATUS_APPROVE_FINANCE)  //主管审批通过时发送邮件
			{
				$this->_send_mail_on_to_finance_approve($new_order);
			}
			elseif($order['status']==ORDER_STATUS_APPROVE&&$new_order['status']==ORDER_STATUS_APPROVE_MANAGER
			)  //财务审批通过时发送邮件
			{
				$this->_send_mail_on_to_manger_approve($new_order);
			}
			elseif(in_array($order['status'],array(ORDER_STATUS_APPROVE,ORDER_STATUS_APPROVE_FINANCE,ORDER_STATUS_APPROVE_MANAGER))&&$new_order['status']==ORDER_STATUS_NO_CONFIRM)  //审批不通过时发送邮件
			{
				$new_order["approve_no_desc"]=$approve_no_desc;
				$this->_send_mail_on_approve_not_pass($new_order);
			}
			elseif(in_array($order['status'],array(ORDER_STATUS_APPROVE,ORDER_STATUS_APPROVE_FINANCE,ORDER_STATUS_APPROVE_MANAGER))&&$new_order['status']==ORDER_STATUS_FACTORY_CONFIRM)  //审批通过时发送邮件
			{
				$this->_send_mail_on_wait_factory_confirm($new_order);
			}
			elseif($order['status']==ORDER_STATUS_FACTORY_CONFIRM&&$new_order['status']==ORDER_STATUS_CONFIRM)  //工厂确认时发送邮件
			{
				$this->_send_mail_on_factory_confirm($new_order);
			}
			
			//工厂报价
			/* if (in_array($user_info['role'], array(USER_MERCHANDISER))){
				$new_quote_id=array();
				
				foreach($_POST['member_name'] as $key=>$items)
				{
					$quote_id=isset($_POST['quote_id'][$key])?intval($_POST['quote_id'][$key]):0;
					$quote_data=array(
							"order_id"=>$id,
							"quote_price"=>isset($_POST['quote_price'][$key])?intval($_POST['quote_price'][$key]):"",
							"factory_id"=>isset($_POST['member_name'][$key])?trim($_POST['member_name'][$key]):"",
					);
				
					$quote_order_id[]=isset($_POST['quote_order_id'])?$_POST['quote_order_id'][$key]:"";
					if(!empty($quote_data['factory_id']) || !empty($quote_data['quote_price']))
					{
						if(empty($quote_id))
						{
							$quote_data['quote_add_time']=gmtime();
							$quote_id=$quote_mod->add($quote_data);
							$file_mod =& m('upload');
							if(!empty($quote_order_id[$key]))
							{
								$file_ids= implode(',', array_filter($quote_order_id));
								$cust_files_info=$file_mod->find(array(
										"conditions"=>"file_id in({$file_ids}) AND file_type=".BELONGS_QUOTE_ORDER." AND key_id=".DEFAULT_CUSTOMER_KEY_ID." and session_id='".session_id()."'"
								));
									
								foreach($cust_files_info as $item)
								{
									$file_path = str_replace(DEFAULT_CUSTOMER_KEY_ID, $quote_id, $item['file_path']);
									if(!file_exists(dirname($file_path))) {
										mkdir(dirname($file_path), 0777);
									}
									rename($item['file_path'], $file_path);
									$file_mod->edit("file_id={$item['file_id']}",array(
											"file_path"=>$file_path,
											"key_id"=>$quote_id,
											"session_id"=>session_id()
									));
								}
							}
						}
						else
						{
							$new_quote_id[]=$quote_id;
				
							$quote_mod->edit("quote_id={$quote_id}",$quote_data);
						}
					}
				
				}
					
				if (!empty($quote_list)){
					foreach($quote_list as $quote_rows)
					{
						if(!in_array($quote_rows['quote_id'],$new_quote_id))
						{
							$quote_mod->drop("quote_id={$quote_rows['quote_id']}");
						}
					}
				}
			} */
			
			//分批收货
			/* if (in_array($user_info['role'], array(USER_MANAGER,USER_QC,USER_FINANCE,USER_OUTGOING))){
				$new_receipt_id=array();
				foreach($_POST['f_name'] as $key=>$items)
				{
					$receipt_id=isset($_POST['receipt_id'][$key])?intval($_POST['receipt_id'][$key]):0;
					$receipt_data=array(
							"order_id"=>$id,
							"factory_id"=>isset($_POST['f_name'][$key])?trim($_POST['f_name'][$key]):"",
							"receipt_num"=>isset($_POST['receipt_num'][$key])?intval($_POST['receipt_num'][$key]):"",
							"shipment_num"=>isset($_POST['shipment_num'][$key])?trim($_POST['shipment_num'][$key]):"",
							"score"=>isset($_POST['score'][$key])?trim($_POST['score'][$key]):"",
							"receipt_date"=>isset($_POST['receipt_date'][$key])?strtotime($_POST['receipt_date'][$key]):"",
					);
				
				
					if(!empty($receipt_data['factory_id']) || !empty($receipt_data['receipt_num']))
					{
						if(empty($receipt_id))
						{
							$receipt_id=$receipt_mod->add($receipt_data);
							$receipt_order_id=isset($_POST['receipt_order_id'])?$_POST['receipt_order_id']:"";
							if(!empty($receipt_order_id[$key]))
							{
								$rec_file_ids=$receipt_order_id[$key];
								$cust_rec_info=$file_mod->find(array(
										"conditions"=>"file_id in({$rec_file_ids}) AND file_type=".BELONGS_RECEIPT_ORDER." AND key_id=".DEFAULT_CUSTOMER_KEY_ID." and session_id='".session_id()."'"
												));
							
								foreach($cust_rec_info as $item)
								{
									$file_path = str_replace(DEFAULT_CUSTOMER_KEY_ID, $receipt_id, $item['file_path']);
									if(!file_exists(dirname($file_path))) {
										mkdir(dirname($file_path), 0777);
									}
									rename($item['file_path'], $file_path);
									$file_mod->edit("file_id={$item['file_id']}",array(
											"file_path"=>$file_path,
											"key_id"=>$receipt_id,
											"session_id"=>session_id()
									));
								}
							}
						}
						else
						{
							$new_receipt_id[]=$receipt_id;
				
							$receipt_mod->edit("receipt_id={$receipt_id}",$receipt_data);
						}
					}
				
				}
					
				if (!empty($receipt_list)){
					foreach($receipt_list as $receipt_rows)
					{
						if(!in_array($receipt_rows['receipt_id'],$new_receipt_id))
						{
							$receipt_mod->drop("receipt_id={$receipt_rows['receipt_id']}");
						}
					}
				}
			} */
			
// 			if ($user_info['role']==USER_OUTGOING){
// 				$qc_id=isset($_POST['sel_qc'])?intval($_POST['sel_qc']):0;
// 				$qc_factory_mod=&m('qcfactory');
// 				if ($qc_id){
// 					$qc_info=$qc_factory_mod->find(array(
// 						'conditions'=>'order_id='.$id
// 					));
// 					$qc_data=array();
// 					$qc_data['order_id']=$id;
// 					$qc_data['user_id']=$qc_id;
// 					if (empty($qc_info)){
// 						$qc_factory_mod->add($qc_data);
// 					}else{
// 						$qc_factory_mod->edit("order_id={$id}",$qc_data);
// 					}
// 					if ($qc_factory_mod->has_error()){
// 						$this->show_warning($qc_factory_mod->get_error());
// 						return;
// 					}
// 				}
// 			}
			
			if ($data['sample_id']){
				if($order['sample_id']!=$data['sample_id']) {
					$sample_mod->edit($data['sample_id'],array('order_id'=>$id,'is_order'=>'1','order_sn'=>$order['order_sn'],'order_create_date'=>$order['order_create_date']));
					if ($order['sample_id']){
						$sample_mod->edit($order['sample_id'],array('order_id'=>0,'is_order'=>'0','order_sn'=>0,'order_create_date'=>0));
					}
				}
			}
            header("location:index.php?app=order&act=edit&id={$id}");
		}
    }
	
    //客户编辑订单
    function consumer_edit(){
    	$order_id=empty($_GET['id'])?0:intval($_GET['id']);
    	$view=isset($_GET['handle'])?trim($_GET['handle']):'';
    	$user=$this->visitor->get();
    	if (!$order_id){
    		$this->show_warning('请选择订单');
    		return;
    	}
    	if ($view=='view'){
    		$this->assign('is_view',true);
    	}
    	$order_info=$this->_order_mod->get($order_id);
    	if (empty($order_info)){
    		$this->show_warning('订单不存在');
    		return;
    	}
    	if (!IS_POST){
    		$this->assign('u_client',USER_CLIENT);
    		//属于客户的品牌
			$member_mod=&m('member');
			$member_info=$member_mod->get_info($this->visitor->get('user_id'));
			$brand_mod=&m('brand');
			$brands=$brand_mod->find(array(
					'join'		=>'belong_company',
					'conditions'=>'brand_id'.db_create_in($member_info['brand_arr_id'])
			));
			$this->assign('brand_list',$brands);

			//目的地
			$brand_addr_name = $brand_mod->get(array('fields'=>'brand_addr','conditions'=>'brand_id='.$order_info['brand_id']));
			$brand_addr_list = explode(",",$brand_addr_name['brand_addr']);
			$this->assign("brand_addr_name",$brand_addr_list);
			
			//买手
			$buyer_list=$member_mod->find(array(
					'conditions'=>'user_id='.$this->visitor->get('user_id').' and role='.USER_CLIENT
			));
			$this->assign('buyer_list',$buyer_list);

			//跟单
			if ($member_info['freight_id']){
				$merchandiser_list=$member_mod->find(array(
						'conditions'=>'user_id='.$member_info['freight_id'].' and role='.USER_MERCHANDISER
				));
			}
			$this->assign('merchandiser_list',$merchandiser_list);
    		
			$disreason_type_mod =& m('disreason_type');
    		$this->assign('disreason_type_list', $disreason_type_mod->find(array('conditions'=>"1=1")));
    			
    		$sample_mod =& m('sample');
    		$this->assign('sample_list', $sample_mod->find(array('order'=>'sample_sn ASC','conditions'=>'buyer_id='.$user['user_id'])));
    			
    		$style_mod =& m('style');
    		$this->assign('style_list', $style_mod->find(array('conditions'=>'if_show=1','order'=>'style_name DESC')));
    			
//     		$factory_mod =& m('factory_info');
//     		$factory_list=$factory_mod->find(array('conditions'=>'factory_id='.DEFAULT_FACTORY_ID,'order'=>'factory_name'));
//     		$this->assign('factory_list', array_filter($factory_list));
    		
    		$file_mod =& m('upload');
    		$file_comment=$file_mod->find(array(
    				'conditions' => 'file_type = ' . BELONGS_CONSUMER_COMMENT_ORDER . ' AND key_id = ' . $order_id.' and session_id="'.session_id().'"',
    				'order' => 'file_id ASC',
    		));
    		$file_remarks=$file_mod->find(array(
    				'conditions' => 'file_type = ' . BELONGS_CONSUMER_REMARKS_ORDER . ' AND key_id = ' . $order_id.' and session_id="'.session_id().'"',
    				'order' => 'file_id ASC',
    		));
    		$this->assign('file_comment',$file_comment);
    		$this->assign('file_remarks',$file_remarks);
    		//客户评语跟备注
    		$this->assign('consumer_comment_order',BELONGS_CONSUMER_COMMENT_ORDER);
    		$this->assign('consumer_remarks_order',BELONGS_CONSUMER_REMARKS_ORDER);
    		
    		$this->assign('order',$order_info);
    		$this->_curlocal(Lang::get('order_list'),'index.php?app=order',Lang::get('edit_order'));
    		$this->display('order.consumer.html');
    	}else{
    		$data=$this->_handle_order_status($_POST['info']);
    		if (!$view){
    			$brand_id=isset($_POST['info']['brand_id'])?intval($_POST['info']['brand_id']):0;
    			$buyer_id=isset($_POST['info']['buyer_id'])?intval($_POST['info']['buyer_id']):0;
    			$merchandiser_id=isset($_POST['info']['merchandiser_id'])?intval($_POST['info']['merchandiser_id']):0;
    			$style_id=isset($_POST['info']['style_id'])?intval($_POST['info']['style_id']):0;
    			
    			$brand_mod =& m('brand');
    			$brand_info= $brand_mod->get($brand_id);
    			
    			$user_mod =& m('member');
    			$buyer_info= $user_mod->get($buyer_id);
    			
    			$merchandiser_info=$user_mod->get($merchandiser_id);
    			$style_mod =& m('style');
    			$style_info= $style_mod->get($style_id);
    			//     		if (empty($brand_info)) {
    			//     			$this->show_warning('请选择品牌');
    			//     			exit();
    			//     		}
    			if (empty($buyer_info)) {
    				$this->show_warning('请选择买手');
    				exit();
    			}
    			if (empty($merchandiser_info)) {
    				$this->show_warning('请选择跟单');
    				exit();
    			}
    			if (empty($style_info)) {
    				$this->show_warning('请选择款式');
    				exit();
    			}
    			$data['brand_name']=$brand_info['brand_name'];
    			$data['buyer_name']=$buyer_info['user_name'];
    			$data['merchandiser']=$merchandiser_info['user_name'];
    			$data['style_name']=$style_info['style_name'];
    		}
    		$this->_order_mod->edit($order_id,$data );
    		if ($this->_order_mod->get_error()) {
    			$this->show_warning($this->_order_mod->get_error());
    			return;
    		}
    		if($data['sample_id']) {
    			if ($order_info['sample_id']!=$data['sample_id']){
    				$sample_mode=&m('sample');
    				$sample_mode->edit($data['sample_id'],array('order_id'=>$id,'is_order'=>'1','order_sn'=>$data['order_sn'],'order_create_date'=>strtotime($data['order_create_date'])));
    				if ($order_info['sample_id']){
    					$sample_mode->edit($order_info['sample_id'],array('order_id'=>0,'is_order'=>'0','order_sn'=>0,'order_create_date'=>0));
    				}
    			}
    		}
    		$this->show_message('edit_order_success');
    	}
    }
    
	//查看订单
	function view()
	{
        $id=$_GET['id']?intval($_GET['id']):0;
        if(!$id) {
            $this->show_warning('请选择订单');
			return;
        }
        $order=$this->_order_mod->get($id);
        if(!$order) {
            $this->show_warning('订单不存在');
			return;
        }
		
		if($this->visitor->get("role")==USER_FACTORY&&$order['factory_id']!=$this->visitor->get("factory_id"))
		{
			$this->show_warning('用户无权限操作此订单');
			return;
		}
		
		//限制那些状态只能哪些角色编辑
		$is_edit=$this->_check_order_is_edit($order);echo $is_edit;
		$this->assign("is_edit",$is_edit);
		
		//添加一个限制条件  
		$factory_role=$this->visitor->get('role');
		if($factory_role == USER_FACTORY and $order['status'] == ORDER_STATUS_FACTORY_CONFIRM){
			//$this->assign('factory_role',true);
		}
		$file_mod=&m('upload');
		$user_info=$this->visitor->get();
		
		//获取对应的制单信息
		$ss_mod =& m('ss');
		$ss_info=$ss_mod->get("order_id={$id}");
		$this->assign("ss_info",$ss_info);
			//赋值进度记录
			$mod_pro_records=&m("pro_records");
			$pro_records_list=$mod_pro_records->find(array(
				'conditions'=>"key_id={$id} AND type=".PRO_RECORDS_ORDER,
				'order'	=>"rec_time desc"
			));
			$this->assign("pro_records_list",$pro_records_list);
			
			//赋值色卡信息
			$colorcard_mode=& m('color_card');
			
			$fabric_shop_list=$colorcard_mode->getall("select fabric_shop_name,fabric_shop_id from {$colorcard_mode->table} group by fabric_shop_id order by fabric_shop_name,update_time desc");

			$this->assign("fabric_shop_list",$fabric_shop_list);
			
			$brand_mod =& m('brand');
			$this->assign('brand_list', $brand_mod->find(array('conditions'=>'if_show=1','join'=>"belong_company",'order'=>'brand_name ASC')));
			$brand_info=$brand_mod->get($order['brand_id']);
			$company_id=!empty($brand_info)?$brand_info['company_id']:0;
			
			$buyer_mod =& m('member');
			$this->assign('buyer_list', $buyer_mod->find(array('conditions'=>'if_show=1 and activation=1 and role='.USER_CLIENT)));
			
			$user_mod =& m('member');
			$this->assign('merchandiser_list', $user_mod->find(array('conditions'=>'if_show=1 AND role='.USER_MERCHANDISER.' AND user_id='.$order['merchandiser_id'])));
// 			$disreason_type_mod =& m('disreason_type');
// 			$this->assign('disreason_type_list', $disreason_type_mod->find(array('conditions'=>"1=1")));

			
			$sample_mod =& m('sample');
			$this->assign('sample_list', $sample_mod->find(array('order'=>'sample_sn ASC')));
			
			$style_mod =& m('style');
			$this->assign('style_list', $style_mod->find(array('conditions'=>'if_show=1','order'=>'style_name DESC')));
			
			$factory_mod =& m('factory_info');
			$this->assign('factory_list', $factory_mod->find(array('join'=>'belongs_factory_member','conditions'=>'if_show=1','order'=>'factory_name DESC')));
			
			$fs_mod =& m('fabric_shop');
			$this->assign('fabricshop_list', $fs_mod->find(array('conditions'=>'if_show=1','order'=>'fabric_shop_name ASC')));
			
			//qc列表
// 			if (in_array($user_info['role'], array(USER_QC,USER_OUTGOING))){
// 				$qc_list=$user_mod->find(array(
// 						'conditions'=>'if_show=1 and role='.USER_QC,
// 						'order'=>'user_name asc'
// 				));
// 				$this->assign('qc_list',$qc_list);
// 				$qc_factory_mod=&m('qcfactory');
// 				$qf=$qc_factory_mod->get("order_id=".$id);
// 				if (!empty($qf)){
// 					$this->assign('qf',$qf['user_id']);
// 				}
// 			}
			
			$quote_mod=& m('quote');
			$page = $this->_get_page(10);
			if ($order['factory_id']==DEFAULT_FACTORY_ID){
				$this->assign('default_factory',true);
				//获取加工工厂的报价信息
				$file_mod=&m('upload');
				$quote_list=$quote_mod->find(array(
						'join'=>'belongs_factory',
						'conditions'=>'order_id='.$id,
						'count'=>true,
						'limit'=>$page['limit']
				));
				if (!empty($quote_list)){
					foreach ($quote_list as $key=>$rows){
						$f_id=$rows['factory_id'];
						$quote_list[$key]['order_num']=$quote_mod->getOne("select sum(order_num) from {$quote_mod->table} where if_option=1 and factory_id=".$f_id);
						$quote_list[$key]['file_quote']=$file_mod->find(array('conditions'=>'file_type = '.BELONGS_QUOTE_ORDER.' AND key_id = '.$rows['quote_id'],'order'=>'file_id ASC'));
					}
				}
				$page['item_count'] = $quote_mod->getCount();
				/* 报价附件 */
				$this->assign('belongs_quote_order', BELONGS_QUOTE_ORDER);
				$this->assign('quote_list',$quote_list);
			}
			
			//显示qc查货进度列表
			$process_mod=& m('qc_process');
			$process_list=$process_mod->find(array(
					'conditions'=>'order_id='.$id,
					'order'=>'receipt_time desc'
			));
			if (!empty($process_list)){
				$member_mod=&m('member');
				foreach ($process_list as $k=>$val){
					$qc_id=$val['qc_id'];
					$mem_info=$member_mod->get($qc_id);
					$process_list[$k]['qc_name']=$mem_info['user_name'];
				}
			}
			$this->assign('process_list',$process_list);
			
			//查看主唛
			if ($order['brand_id']){
				$this->_assign_main_label($order['brand_id']);
				$this->_assign_listing($order['brand_id']);
			}
			
		if (IS_POST) {
			$submit_val= trim($_POST['submit']);
			$data=array();
			if ($user_info['role']==USER_CIVILIAN){
				$data['is_keep_sample']=trim($_POST['is_keep_sample']);
			}
			$mod_pro_records=&m("pro_records");
			$log_time=gmtime();
			$approve_no_desc=isset($_POST['approve_no_desc'])?trim($_POST['approve_no_desc']):"";
			switch($order['status'])
			{
				case ORDER_STATUS_FACTORY_CONFIRM:		//工厂确认
				  if ($submit_val=="确认订单") {
						  $data['status'] = ORDER_STATUS_CONFIRM;
						  $pro_data=array(
							  "type"=>PRO_RECORDS_ORDER,
							  "key_id"=>$id,
							  "rec_name"=>$this->visitor->get("user_name"),
							  "rec_buff"=>"工厂确认",
							  "rec_time"=>$log_time			
						  );
						if(!$mod_pro_records->add($pro_data))
						{
						   $this->show_warning($mod_pro_records->get_error());
						}
					}
				break;

			}
			
			if($submit_val=="重置" && in_array($this->visitor->get("role"), array(USER_MANAGER,USER_MERCHANDISER_ADMIN)))
			{
				$data['status'] = ORDER_STATUS_NO_CONFIRM;
				$pro_data=array(
						"type"=>PRO_RECORDS_ORDER,
						"key_id"=>$id,
						"rec_name"=>$this->visitor->get("user_name"),
						"rec_buff"=>"重置订单",
						"rec_time"=>$log_time
				);
				if(!$mod_pro_records->add($pro_data))
				{
					$this->show_warning($mod_pro_records->get_error());
				}
			}
			
			$this->_order_mod->edit($id,$data );
			if ($this->_order_mod->get_error()) {
				$this->show_warning($this->_order_mod->get_error());
				return;
			}
			
			//当送审批等状态发送对应的邮件
			$new_order=$this->_order_mod->get($id);
			if($order['status']==ORDER_STATUS_FACTORY_CONFIRM&&$new_order['status']==ORDER_STATUS_CONFIRM)  //工厂确认时发送邮件
			{
				$this->_send_mail_on_factory_confirm($new_order);
			}
			 header("location:index.php?app=order&act=view&id={$id}");
		}
			
		if (!empty($order)){
			$order['contract_file']=$file_mod->find(array(
					'conditions'=>'key_id='.$id.' and file_type='.BELONGS_QUOTE_CONTRACT,
					'fields'=>'file_id,file_name'
			));
			$order['cut_file']=$file_mod->find(array(
					'conditions'=>'key_id='.$id.' and file_type='.BELONGS_CUT_ORDER,
					'fields'=>'file_id,file_name'
			));
			$order['statement_list']=$file_mod->find(array(
					'conditions'=>'key_id='.$id.' and file_type='.BELONGS_STATEMENT_FILE,
					'fields'=>'file_id,file_name'
			));
		}
		$this->assign('belongs_state_file',BELONGS_STATEMENT_FILE);
		$this->_format_page($page);
		$this->assign('page_info', $page);
		$this->assign('quote_list',$quote_list);
		$this->_assign_files($order['order_id'], $order['sample_id']);
		$this->assign('order', $order);
		$this->assign('user', $user_info);
		$this->assign('role', $this->visitor->get('role'));
		$this->assign('page_title', '订单信息');
        $this->display('order.print.html');
	}
	
	function _handle_order_status($data)
	{
		if (!isset($data['chb_bd'])) $data['chb_bd'] = '';
		if (!isset($data['chb_jgqr'])) $data['chb_jgqr'] = '';
		if (!isset($data['chb_pbqr'])) $data['chb_pbqr'] = '';
		if (!isset($data['chb_dhb'])) $data['chb_dhb'] = '';
		if (!isset($data['chb_cc'])) $data['chb_cc'] = '';
		if (!isset($data['chb_wc'])) $data['chb_wc'] = '';
		if (!isset($data['chb_ctb'])) $data['chb_ctb'] = '';
		if (!isset($data['is_upload_tm'])) $data['is_upload_tm'] = '0';
		return $data;
	}
	
	function _assign_files($id, $factory = 0)
	{
		$file_mod =& m('upload');
		
		/* 报价单 */
		if ($factory) {
			$this->assign('file_price', $file_mod->find(array('conditions'=>'file_type ='.BELONGS_FACTORY.' AND key_id = '.$factory,'order' => 'file_id ASC',)));
			$this->assign('belongs_price', BELONGS_FACTORY);
		}
		/* 批改意见 */
		$this->assign('file_pigai', $file_mod->find(array('conditions'=>'file_type = '.BELONGS_PIGAI.' AND key_id = '.$id,'order'=>'file_id ASC')));
		$this->assign('belongs_pigai', BELONGS_PIGAI);
		/* 合同信息 */
		$this->assign('file_hetong', $file_mod->find(array('conditions'=>'file_type = '.BELONGS_HETONG.' AND key_id = '.$id,'order'=>'file_id ASC')));
		$this->assign('belongs_hetong', BELONGS_HETONG);
		/* 制单信息 */
		$this->assign('file_zhidan', $file_mod->find(array('conditions'=>'file_type = '.BELONGS_ZHIDAN.' AND key_id = '.$id,'order'=>'file_id ASC')));
		$this->assign('belongs_zhidan', BELONGS_ZHIDAN);
		/* 查货报告 */
		$this->assign('file_chahuo', $file_mod->find(array('conditions'=>'file_type = '.BELONGS_CHAHUO.' AND key_id = '.$id,'order'=>'file_id ASC')));
		$this->assign('belongs_chahuo', BELONGS_CHAHUO);
		/* 扣款信息 */
		$this->assign('file_koukuan', $file_mod->find(array('conditions'=>'file_type = '.BELONGS_KOUKUAN.' AND key_id = '.$id,'order'=>'file_id ASC')));
		$this->assign('belongs_koukuan', BELONGS_KOUKUAN);
		/* 担保走货 */
		$this->assign('file_danbao', $file_mod->find(array('conditions'=>'file_type = '.BELONGS_DANBAO.' AND key_id = '.$id,'order'=>'file_id ASC')));
		/* 质检报告 */
		$this->assign('file_qcreport', $file_mod->find(array('conditions'=>'file_type = '.BELONGS_ORDER_QC_REPORT.' AND key_id = '.$id,'order'=>'file_id ASC')));
		$this->assign('belongs_qcreport', BELONGS_ORDER_QC_REPORT);
		
		/* 折扣原因附件 */
		$this->assign('file_disreason', $file_mod->find(array('conditions'=>'file_type = '.BELONGS_ORDER_DIS_REASON.' AND key_id = '.$id,'order'=>'file_id ASC')));
		$this->assign('belongs_disreason', BELONGS_ORDER_DIS_REASON);
		
		/* 备注附件 */
		$this->assign('file_beizhu', $file_mod->find(array('conditions'=>'file_type = '.BELONGS_ORDER_BEIZHU.' AND key_id = '.$id,'order'=>'file_id ASC')));
		$this->assign('belongs_beizhu', BELONGS_ORDER_BEIZHU);
		
		$this->assign('file_comment',$file_mod->find(array('conditions' => 'file_type = ' . BELONGS_CONSUMER_COMMENT_ORDER . ' AND key_id = ' . $id.' and session_id="'.session_id().'"','order' => 'file_id ASC')));
		$this->assign('file_remarks',$file_mod->find(array('conditions' => 'file_type = ' . BELONGS_CONSUMER_REMARKS_ORDER . ' AND key_id = ' . $id.' and session_id="'.session_id().'"','order' => 'file_id ASC',
		)));
		//客户评语跟备注
		$this->assign('consumer_comment_order',BELONGS_CONSUMER_COMMENT_ORDER);
		$this->assign('consumer_remarks_order',BELONGS_CONSUMER_REMARKS_ORDER);
		
		
		$this->assign('belongs_danbao', BELONGS_DANBAO);
		
	}
	
    function addsourcing() {//添加采购项
        $this->_ican('add_sourcing');
        $order_id=$_REQUEST['order_id']?intval($_REQUEST['order_id']):'0';
        if(!$order_id) {
            $this->msg_error('无效订单');
            exit;
        }
        $order=$this->_order_mod->get($id);
        if(!$order) {
            $this->msg_error('订单不存在');
            exit;
        }
        $sourcing_mod=&m('sourcing');
        $sourcing=$sourcing_mod->get(array('conditions'=>'key_id='.$order_id .' and type='.SOURCING_LIST_TYPE_ORDER));
        if(empty ($sourcing)) {
            $sid=$sourcing_mod->add(array('type'=>SOURCING_LIST_TYPE_ORDER,'key_id'=>$order_id,'list_sn'=>$this->create_sourcing_list_sn()));
        }
        else {
            $sid=$sourcing['list_id'];
        }
        if(IS_POST) {
            $sitem=&m('sourcingitem');
            $info=$_POST['s_info'];
            // exit;
            $info['list_id']=$sid;
            if(!$info['item_id']) {
                $item_id=$sitem->add($info);
                if($item_id) {
                    $info['item_id']=$item_id;
                    $this->msg_ok($info,'添加成功');
                    exit;
                }
                else {
                    $this->msg_error($sitem->get_error());
                    exit;
                }
            }
            else {
                $sitem->edit(intval($info['item_id']),$info);
                $this->msg_ok($info,'修改成功');
                exit;
            }
        }
    }
    function drop_sourcing_item() {
        $id=intval($_GET['id']);
        $sitem=&m('sourcingitem');
        $item=$sitem->drop($id);
        $this->msg_ok($item, 'ok');
        exit;
    }
    function get_sourcing_item() {
        $this->_ican('add_sourcing_item');
        $id=intval($_GET['id']);
        if(!$id) {
            $this->msg_error('没有此项');
            exit;
        }
        $sitem=&m('sourcingitem');
        $item=$sitem->get($id);
        if(!$item) {
            $this->msg_error('没有此项');
            exit;
        }
        $this->msg_ok($item, 'ok');
    }
    function update_status() {
		
		$role=$this->visitor->get("role");
		
        $this->_ican('dahuo');
        $id=$_REQUEST['id']?intval($_REQUEST['id']):0;
        if(!$id) {
            $this->msg_error( '请选择订单');
            exit;
        }

        $info['status']=intval($_GET['status']);
        if(in_array($info['status'],array('2','3','5'))) {
            switch($info['status']) {
                case '2'://确认
                    $info['confirm_date']=TIME;
                    break;
                case '3'://确认出货
					if($role==USER_FACTORY)
					{
						$this->msg_error( '无权限进行此操作!');
						exit;
					}
                    //$info['send_date']=TIME;
                    $info['submit_date']=TIME;
                    break;
                case '5'://取消
					if($role==USER_FACTORY)
					{
						$this->msg_error( '无权限进行此操作!');
						exit;
					}
		
                    $info['cancel_date']=TIME;
                    break;
            }
            /*if($info['status']=='3'){
                unset($info['status']);
            }*/
            $this->_order_mod->edit($id,$info);
            $info['date']=date('Y-m-d',TIME);
            $this->msg_ok($info,'更新完成');
            exit;
        }
    }
    function dahuo() {
        $this->_ican('dahuo');
        $id=$_REQUEST['order_id']?intval($_REQUEST['order_id']):0;
        if(!$id) {
            $this->msg_error( '请选择订单');
            exit;
        }
        if(IS_POST) {
            $info=$_POST['info'];
            if($info) {
                //print_r($info);exit;
                $this->_order_mod->edit($id,$info);
                $this->msg_ok($info,'更新完成');
                exit;
            }
        }
        else {
            $this->msg_ok($info,'更新完成');
            exit;
        }
    }
    function pingding() {
        $this->_ican('pingding');
        $id=$_REQUEST['order_id']?intval($_REQUEST['order_id']):0;
        if(!$id) {
            $this->msg_error( '请选择订单');
            exit;
        }
        if(IS_POST) {
            $info=$_POST['info'];
            if($info) {
                //print_r($info);exit;
                $this->_order_mod->edit($id,$info);
                $this->msg_ok($info,'更新完成');
                exit;
            }
        }
        else {
            $this->msg_ok($info,'更新完成');
        }
    }
    function addPP() {
        $this->_ican('add_pp');
        $order_id=intval($_REQUEST['order_id']);
        if(!$order_id) {
            $this->msg_error('订单无效');
            exit;
        }
        $arr=array('price'=>$_POST['price'],'again'=>$_POST['again']?'1':'0','datetime'=>$_POST['date'],'order_id'=>$order_id,'number'=>$_POST['number'],'remark'=>$_POST['remark']);
        $pp_mode=&m('pp');
        $sql = "SELECT COUNT(*) FROM ".$pp_mode->table."  where order_id='$order_id' and again=0";
        $total_count = $pp_mode->getOne($sql);
        if($total_count>0) {
            $this->msg_error('不用再版');
            exit;
        }
        $pp_id=intval($_GET['pp_id']);
        if(!$pp_id) {
            $return=$pp_mode->add($arr);
            if(!$pp_mode->get_error()) {
                $arr['pp_id']=$return;
                $this->msg_ok($arr,' 添加完成');
                exit;
            }
            else {
                $this->msg_error($pp_mode->get_error());
            }
        }
        else {
            $pp_mode->edit($pp_id,$arr);
            $arr['pp_id']=$pp_id;
            if(!$pp_mode->get_error()) {
                $this->msg_ok($arr,' 编辑完成');
                exit;
            }
            else {
                $this->msg_error($pp_mode->get_error());
                exit;
            }
        }
    }
    function del_pp() {
        $this->_ican('add_pp');
        $pp_id=intval($_GET['pp_id']);
        $pp_mode=&m('pp');
        $pp_mode->drop($pp_id);
        $arr['pp_id']=$pp_id;
        if(!$pp_mode->get_error()) {
            $this->msg_ok($arr,' 删除完成');
            exit;
        }
    }
    function add_huobu(){
        $this->_ican('add_pp');
        $order_id=intval($_REQUEST['order_id']);
        if(!$order_id) {
            $this->msg_error('订单无效');
            exit;
        }
        $arr=array('send_date'=>$_POST['send_date'],'reply_date'=>$_POST['reply_date'],'order_id'=>$order_id,'number'=>$_POST['number']);
        $hb_mode=&m('huobu');
        $id=intval($_GET['id']);
        if(!$id) {
            $return=$hb_mode->add($arr);
            if(!$hb_mode->get_error()) {
                $arr['id']=$return;
                $this->msg_ok($arr,' 添加完成');
                //$this->update_order_huobu_date($order_id);
            }
            else {
                $this->msg_error($hb_mode->get_error());
            }
        }
        else {
            $hb_mode->edit($id,$arr);
            $arr['id']=$id;
            if(!$hb_mode->get_error()) {
                $this->msg_ok($arr,' 添加完成');
                //$this->update_order_huobu_date($order_id);
            }
            else {
                $this->msg_error($hb_mode->get_error());
            }
        }
    }
    function del_huobu() {
        $this->_ican('add_pp');
        $id=intval($_GET['id']);
        $hb_mode=&m('huobu');
        $hb_mode->drop($id);
        $arr['id']=$id;
        if(!$hb_mode->get_error()) {
            $this->msg_ok($arr,' 删除完成');
            exit;
        }
    }
    function update_order_huobu_date($order_id){
            $hb_mode=&m('huobu');
          $this->_order_mod->db->query('UPDATE '.$this->_order_mod->table.' set reply_bulk_date=unix_timestamp((select max(reply_date) from '.$hb_mode->table.' where order_id=\''.$order_id.'\')) where order_id=\''.$order_id.'\'' );
    }
     function update_order_pp_date($order_id){
          $hb_mode=&m('pp');
          $this->_order_mod->db->query('UPDATE '.$this->_order_mod->table.' set reply_bulk_date=unix_timestamp((select max(reply_date) from '.$hb_mode->table.' where order_id=\''.$order_id.'\')) where order_id=\''.$order_id.'\'' );
    }
    function order_status() {
        $this->_ican('order_status');
        $id=$_REQUEST['id']?intval($_REQUEST['id']):0;
        if(!$id) {
            $this->msg_error( '请选择订单');
            exit;
        }
        $order=$this->_order_mod->get($id);
        if(!$order) {
            $this->show_warning('订单不存在');
        }if
        (!IS_POST) {
            $pp_mode=&m('pp');
            $pp_list=$pp_mode->findAll(array('conditions'=>"order_id='$id'",'order'=>'pp_id asc'));
            $order['left_days']=$orders['buyer_arrival_date']?ceil(($orders['buyer_arrival_date']-TIME)/3600/24):'--';
            $pp_mode=&m('pp');
            $sql = "SELECT COUNT(*) FROM ".$pp_mode->table."  where order_id='$id' and again=0 order by number asc";
            $total_count = $pp_mode->getOne($sql);
            $this->assign('can_add_pp', $total_count>0?'0':'1');
            $hb_mode=&m('huobu');
            $huobus=$hb_mode->find(array('conditions'=>'order_id=\''.$id.'\'','order'=>'number asc'));
			$file_mod =& m('upload');
			$order['chahuo_file'] = $file_mod->find(array(
				'conditions' => 'key_id = ' . $order['order_id'] . ' AND file_type = ' . BELONGS_CHAHUO,
			));
            $this->assign('dahuobu', $huobus);
            $this->assign('order', $order);
            $this->assign('pp_list', $pp_list);
            $this->display('order.status.html');
        }
        else {
            $this->_ican('update_order_status');
            $data=$_POST['info'];
            $data=$this->_handle_post_info($data);
            if($data['status']==2) {
                //$data['is_confirm']=1;
                //$data['confirm_date']=date('Y-m-d',TIME);
            }
            $this->_order_mod->edit($id,$data);
            $this->update_order_huobu_date($id);
            if( !$this->_order_mod->get_error()) {
                $this->msg_ok($data,' 更新完成');
                return;
            }
            $this->msg_error($this->_order_mod->get_error());
        }
    }
	function edit_order_status()
	{
		if (IS_POST) {
			$order_id = empty($_POST['order_id']) ? 0 : intval($_POST['order_id']);
			if (!$order_id) {
				echo ecm_json_encode(array('result'=>'false', 'msg'=>'订单不存在'));
				return;
			}
			$order = $this->_order_mod->get_info($order_id);
			if (!$order) {
				echo ecm_json_encode(array('result'=>'false', 'msg'=>'订单不存在'));
				return;
			}
			$data = array(
				'ref_sample' => trim($_POST['ref_sample']),
				'made_price' => trim($_POST['made_price']),
				'color_card' => trim($_POST['color_card']),
				'bulk' => trim($_POST['bulk']),
				'before_sample' => trim($_POST['before_sample']),
				'description' => trim($_POST['description'])
			);
			$this->_order_mod->edit($order_id, $data);
			echo ecm_json_encode(array('result'=>'true', 'msg'=>'更新完成'));
		} else {
			echo ecm_json_encode(array('result'=>'false', 'msg'=>'更新失败'));
		}
	}
    function chuhuo_list() {
        $this->display('order.chuhuo.html');
    }
    function _assign_common_info() {
        $this->_assign_factory();
        $this->_assign_brand();
    }
    function _assign_other_info() {
        $this->assign('fabrics',$this->_order_mod->get_common_data('fabric_shop'));
        $member_mod=&m('member');//采购员
        $caigou=$member_mod->find(array('conditions'=>'role='.USER_SOURCING));
        $this->assign('caigou',$caigou);

    }
    function _assign_order_dedial_info() {
        $fabric_mod =& m('fabric');
        $this->assign('fabric_list', $fabric_mod->find(array('conditions'=>'if_show = 1', 'order'=>'fabric_name ASC')));
        $feature_mod =& m('feature');
        $this->assign('feature_list', $feature_mod->find(array('conditions'=>'if_show = 1', 'order'=>'feature_name ASC')));
        $this->assign('styles',$this->_order_mod->get_common_data('style'));
        $this->assign('samples',$this->_order_mod->get_common_data('sample'));
        $this->assign('specials',$this->_order_mod->get_common_data('special'));
        $this->assign('buyers',$this->_order_mod->get_common_data('member'));
        // print_r($this->_order_mod->get_common_data);
    }

    function _handle_post_info($post) {
        $post=$this->_format_order($post);
        return $post;
    }
    function _format_time($time) {
        if(!$time) {
            return '';
        }
        else {
            return strtotime($time);
        }
    }
    function _format_order($order) {
        return $this->_order_mod->_format_order($order);
    }
    // function _format_
    function getsample() {
        $id=intval($_GET['id']);
        !$id &&  $this->msg_error('此样板不存在');
        $data=&m('sample')->get_info($id);
        if(!empty($data)) {
            $data['arrival_date']=$data['arrival_date']?date('Y-m-d',$data['arrival_date']):'';
			$file_mod =& m('upload');
			$data['factory_files'] = $file_mod->find(array('conditions'=>'file_type ='.BELONGS_FACTORY.' AND key_id = '.$id,'order' => 'file_id ASC'));
			echo ecm_json_encode(array('done'=>true,'msg'=>'OK','retval'=>$data));
            //$this->msg_ok($data, 'ok');
        }
        else {
            $this->msg_error('此样板不存在');
        }
    }

    
    //根据style_sn找下面的order_sn
    function get_order_list(){
    	$style_sn = $where = null;
    	$style_sn=isset($_GET['style_sn'])?trim($_GET['style_sn']):"";
    	!$style_sn && $this->msg_error('此订单不存在');
    	if ($this->visitor->get('role')==USER_CLIENT){
    		$where = "style_sn='{$style_sn}' AND style_sn='{$style_sn}' and buyer_id=".$this->visitor->get('user_id');
    	}else{
    		$where = "style_sn='{$style_sn}' AND style_sn='{$style_sn}'" ;
    	}
    	$data=$this->_order_mod->find(array(
    		'conditions'=>$where,
    		'fields'=>'order_id,order_sn',
    		'order'=>'add_time desc'		
    	));
    	//echo $where;
    	if(!empty($data)) {
    		echo ecm_json_encode(array('done'=>true,'msg'=>'OK','retval'=>$data));
    		//$this->msg_ok($data, 'ok');
    	}else{
    		echo ecm_json_encode(array('done'=>false,'msg'=>'订单不存在'));
    	}
    }
    
 	function getorder() {
 		$order_id = $where = null;
        $order_id=isset($_GET['order_id'])?trim($_GET['order_id']):"";
        !$order_id &&  $this->msg_error('此订单不存在');
        $where = "order_id={$order_id} AND order_id={$order_id}" ;        
        $data=$this->_order_mod->get($where);
        //echo $where;
        if($data) {
			$data['release_date']=gmtimeshow($data['release_date'],"Y-m-d");
			$data['buyer_arrival_date']=gmtimeshow($data['buyer_arrival_date'],"Y-m-d");
			echo ecm_json_encode(array('done'=>true,'msg'=>'OK','retval'=>$data));
            //$this->msg_ok($data, 'ok');
        }
        else {
            $this->msg_error('此订单不存在');
        }
    }
    function get_sourcing_list() {
        $order_id=$_GET['order_id']?intval($_GET['order_id']):'0';
        if(!$order_id) {
            $this->msg_error('订单不存在'.$order_id);
            exit;
        }
        $sourcing_mod=&m('sourcing');
        $sourcing=$sourcing_mod->get(array('conditions'=>'key_id='.$order_id .' and type='.SOURCING_LIST_TYPE_ORDER));
        $sitem=&m('sourcingitem');
        $sourcing_item_list=$sitem->find(array('conditions'=>'list_id=\''.$sourcing['list_id'].'\''));
        $fabrics=$this->_order_mod->get_common_data('fabric_shop');
        $s='';
        $i=0;
        foreach($sourcing_item_list as $k=>$sc) {
            $i++;
            $s.="<tr bgcolor=\"#f4f8fa\" type=\"data\" id=\"tr_sourcing_item_{$sc['item_id']}\">
                <td>$i</td>
                <td>{$sc['fabric_info']}</td>
                <td>{$fabrics[$sc['fabric_shop_id']]['fabric_shop_name']}</td>
                <td><input type=\"button\" onclick=\"edit_sourcing_item('{$sc['item_id']}');\" value=\"修改\" class=\"btn-s-1\">&nbsp;<input type=\"button\" onclick=\"del_sourcing_item('{$sc['item_id']}');\" value=\"删除\" class=\"btn-s-1\">&nbsp;</td>
                </tr>";
        }
        exit ($s);
    }
    /* 工厂列表 */
    function _assign_factory() {
	    $user = $this->visitor->get();
	    $factory_mod = &m('factory_info');
		if ($user['role'] == USER_QC){
				$qf_mod = & m('qcfactory');
				$qf_list = $qf_mod->find(array(
						'fields' => 'factory_id',
						'conditions' => 'user_id='.$user['user_id']
				));
				$arr_info = '';
				if($qf_list){
					$arr = array();
					foreach($qf_list as $key=>$value){
						$arr[$key] = $value['factory_id'];
					}
					$arr_info = implode(",",array_unique($arr));
					if (!empty($arr_info)){
						$order_list=$this->_order_mod->find(array(
							'fields'=>'factory_id',
							'conditions'=>'factory_id in('.$arr_info.')'	
						));
						if (!empty($order_list)){
							$order_arr=array();
							foreach ($order_list as $keys=>$item){
								$order_arr[$keys]=$item['factory_id'];
							}
							$factory_arr=implode(',', array_unique($order_arr));
						}
					}
				}

				if(empty($factory_arr)){
					$where = "factory_info.factory_id in('') and activation=1";
				}else{
					$where = "factory_info.factory_id in(".$factory_arr.") and activation=1";
				}
				$this->assign('factory_list',$factory_mod->find(array('fields'=>'factory_info.factory_id,factory_info.factory_name','conditions'=>$where,'join'=>'belongs_factory_member')));
		}elseif ($user['role']==USER_CLIENT){
			$this->assign('factory_list', $factory_mod->find(array('fields'=>'factory_info.factory_id,factory_info.factory_name','conditions'=>'factory_info.factory_id='.DEFAULT_FACTORY_ID.' and activation=1','join'=>'belongs_factory_member')));
		}else{
			$this->assign('factory_list',$factory_mod->find(array('fields'=>'factory_info.factory_id,factory_info.factory_name','conditions'=>'activation=1','join'=>'belongs_factory_member')));
		}
        
    }
    /* 品牌列表 */
    function _assign_brand() {
		$brand_mod =& m('brand');
		if($this->visitor->get("role")==USER_MANAGER && $_GET['act']!="search")
		{
			$mod_company_manager=&m("company_manager");
			$brand_where=" AND brand.company_id in(select company_id from {$mod_company_manager->table} where uid={$this->visitor->get('user_id')})";
		}elseif ($this->visitor->get("role")==USER_CLIENT){
			$member_mod=&m('member');
			$member_info=$member_mod->get_info($this->visitor->get('user_id'));
			$brand_where=' and brand_id'.db_create_in($member_info['brand_arr_id']);
		}
		$brand_list = $brand_mod->find(array(
			'conditions' => 'if_show = 1'.$brand_where,
			'join'=>"belong_company",
			'order' => 'brand_name ASC'
		));
        $this->assign('brand_list',$brand_list);
    }
    function _time_out_put($time,$format='Y-m-d',$replace='') {
        return $time>0?date($format,$time):$replace;
    }

    function msg_error($msg, $retval='', $jqremote='') {
        if(IS_AJAX) {
            $this->json_error($msg, $retval, $jqremote);
        }
        else {
            $this->show_warning($msg);
        }
		exit;
    }
    function msg_ok($retval,$msg='', $jqremote='') {
        if(IS_AJAX) {
            $this->json_result($retval,$msg,  $jqremote);
        }
        else {
            $this->show_message($msg);
        }
		exit;
    }
    function _ican($action,$output=true) {
        $can=false;
        switch ($action) {
            case 'order_search':
                $can=true;
                break;
            case 'dahuo':
                $can=$this->check_powers(array(USER_MANAGER,USER_MERCHANDISER),$output);
                break;
            case 'pingding':
                $can=$this->check_powers(USER_MANAGER,$output);
                break;
            case 'view_order_list':
            case 'order_status_search':
            case 'order_status':
			    //print_r(array(USER_MANAGER,USER_MERCHANDISER));
                $can=$this->check_powers(array(USER_ASSISTANT,USER_MANAGER,USER_MERCHANDISER),$output);
                break;
            case 'add_sourcing':
            case 'add_sourcing_item':
            case 'edit_order':
            case 'add_order':
            case 'add_pp';
            case 'update_order_status':
                $can=$this->check_powers(USER_MERCHANDISER,$output);
                break;
        }
        return $can;
    }

    function search() {
		set_time_limit (0);
        $this->_ican('order_search');
        $page=$_GET['page']?intval($_GET['page']):'1';
        $perpage=PERPAGE;
        $start=($page-1)*$perpage;
        $start<0 && $start=0;
	   $this->_curlocal("订单查询");
	   $fabric_shop_id = empty($_GET['fabric_shop_id']) ? 0 : intval($_GET['fabric_shop_id']);
	   $factory_item = empty($_GET['factory_item']) ? "" : trim($_GET['factory_item']);
	   $fabric_info_mod = &m('fabric_info');
	   $ss_mod = &m('ss');
		$color_card_info_list=array();
		if(empty($fabric_shop_id))
		{
			$color_card_info_list=$fabric_info_mod->getall("select item from {$fabric_info_mod->table} group by item order by item");
		}
		else
		{
			$color_card_info_list=$fabric_info_mod->getall("select item from {$fabric_info_mod->table} where fabric_shop_id={$fabric_shop_id} group by item order by item") ;

		}

		$color_card_info_list_val=array();
		foreach($color_card_info_list as $key=>$value){
			$color_card_info_list_val[$key]['item'] = $value['item'];
		}
		$this->assign('color_card_info_list',$color_card_info_list_val);
		
        $condition=$this->_get_conditions();

		 /* 获取跟单 */
// 		$merch_mod =& m('member');
// 		$merch_list = $merch_mod->find(array(
// 			'conditions' => 'role = ' . USER_MERCHANDISER . ' AND if_show = 1' . ($this->visitor->get('role') == USER_ASSISTANT ? ' AND user_id in (' . $this->visitor->get('merchandiser') . ')' : ''),
// 			'order' => 'user_name',
// 		));
// 		$this->assign('merchandiser_list', $merch_list);
        $qc_mod=&m('qcfactory');
		$user = $this->visitor->get();
		$this->assign("user",$user);
		if (in_array($user['role'], array(USER_MERCHANDISER_ADMIN))) {
//			$this->assign('user_manage', USER_MANAGER);
//			$merch_id = empty($_GET['merch_id']) ? 0 : intval($_GET['merch_id']);
//			if ($merch_id) {
//				$conditions[] = "merchandiser_id = $merch_id";
//			}
			$conditions[] = "1=1";
// 		   $mod_company_manager=&m("company_manager");
// 			$brand_mod =& m('brand');
// 			$conditions[]="o.brand_id in(select brand_id from {$brand_mod->table} where company_id in(select company_id from {$mod_company_manager->table} where uid={$this->visitor->get('user_id')}))";
			
		} elseif ($user['role'] == USER_ASSISTANT) {
			$merch_id = empty($_GET['merch_id']) ? 0 : intval($_GET['merch_id']);
			$this->assign('user_assistant', USER_ASSISTANT);
			$merch_ids = $user['user_id'];
			if ($merch_id) {
				$conditions[] = "merchandiser_id = $merch_id";
			} else {
				$conditions[] = "merchandiser_id in ($merch_ids)";
			}
		}
		elseif ($user['role'] == USER_FACTORY) {
			if (!$user['factory_id']){
				$this->show_warning('没有该工厂,如有疑问,请联系管理员');
				return;
			}
			$conditions[] = "factory_id = {$this->visitor->get('factory_id')}";
		}elseif ($user['role'] == USER_QC){
			$conditions[] = "1=1";
			//$conditions[] = $this->qc_factory_info($user);
		}elseif ($user['role']==USER_CLIENT){
			$status_str="status not in(".ORDER_STATUS_NO_CANCEL.",".ORDER_STATUS_PAY_MONEY.")";
			$condition.=!empty($condition)?" AND {$status_str}":$status_str;
			$merch_id = $user['user_id'];
			$conditions[] = "1=1";
			$conditions[] = "buyer_id = $merch_id";
		}elseif ($user['role']==USER_OUTGOING){
			//$conditions[]="1=1";
			//$conditions[] =$this->qc_factory_info();
			$conditions[] = "1=1";
		}elseif ($user['role']==USER_CHUANWU){
			$conditions[]="1=1";
		}elseif ($user['role']==USER_MANAGER){
			$conditions[]="1=1";
		}
		 else {
			$merch_id = $user['user_id'];
			$conditions[] = "1=1";
			//$conditions[] = "merchandiser_id = $merch_id";
		}
	
		if (!empty($fabric_shop_id) || !empty($factory_item)) {
			$where_str=!empty($fabric_shop_id)?"fabric_shop_id={$fabric_shop_id}":"";
			$where_str=(!empty($where_str)&&!empty($factory_item)?$where_str." AND ":$where_str).(!empty($factory_item)?"item ='{$factory_item}'":"");
			$s_sql="select ss_id from {$fabric_info_mod->table} where {$where_str} group by ss_id";
			$res=$fabric_info_mod->getAll($s_sql);
			$result=array();
			if (!empty($res)){
				foreach ($res as $row){
					$result[]=$row['ss_id'];
				}
			}
			if (!empty($result)){
				$sql_str="select order_id from {$ss_mod->table} where ss_id in(".implode(',', $result).")";
				$conditions[] = 'order_id in(' . $sql_str . ')';
			}
		}
		
		if ($this->_role==USER_MANAGER || ($this->_role==USER_MERCHANDISER && $this->visitor->get('role_cate')==ROLE_MERCH)){
			if (!empty($_GET['assign_buyer'])){
				$conditions[]='FIND_IN_SET('.$_GET['assign_buyer'].',consumer_arr_id)';
				$this->assign('cancel_user',$_GET['assign_buyer']);
			}
		}
		
		//订单统计
		$year=isset($_GET['year'])?$_GET['year']:'';
		$month=isset($_GET['month'])?$_GET['month']:'';
		if ($year && $month){
			$conditions[]='order_create_date >= ' . strtotime($year .'-'. $month.'-1') . ' AND order_create_date <= ' . strtotime($year.'-'.$month.'-31');
			$this->assign('c_time1',$year.'-'.$month.'-1');
			$this->assign('c_time2',$year.'-'.$month.'-31');
			$this->assign('mer_id',$_GET['merchandiser_id']);
			$this->assign('status',$_GET['status']);
		}
		
		$conditions = ($condition ? ' AND ' : '') . implode(' AND ', $conditions);
		
		if($user['role']==3 || $user['role']==7|| $user['role']==USER_FACTORY || $user['role']==USER_QC)
		{
		   $condition = $condition . $conditions;
		}else{
			$condition .= $conditions;
		}
		if(!empty($_GET['sample_sn'])){
			empty($condition)&&$condition="1=1";
			$condition .= " AND sample_sn like '%".$_GET['sample_sn']."%'";
		}
		
		if(!empty($_GET['qc_id'])){
			$qc_id=$_GET['qc_id'];
			$qc_factory=$qc_mod->find(array('conditions'=>'user_id='.$qc_id));
			if (!empty($qc_factory)){
				foreach ($qc_factory as $rows){
					$qc_factory_arr[]=$rows['factory_id'];
				}
			}
			$condition .=" and factory_id".db_create_in($qc_factory_arr);
		}
		
		$order = empty($_GET['order']) ? 'add_time DESC' : str_replace('-', ' ', trim($_GET['order']));
		if ($order != 'order_create_date DESC' || $order != 'order_create_date ASC') {
			$order .= ', add_time DESC';
		}
		//echo $condition;
		$orders=array();
  		if(isset($_GET['search']))
  		{
		  $orders=$this->_order_mod->find(
				  array(
				  'limit'=>"$start,$perpage",
				  'conditions'=>$condition.' and status!='.ORDER_STATUS_PAY_MONEY,
				  'count' => true,
				  'order' => $order.',style_sn desc',
				  )
		  );
  		}
		foreach($orders as $key=>$item)
		{
			$orders[$key]["is_edit"]=$this->_check_order_is_edit($item);
		}
       // $sql = "SELECT COUNT(*) FROM {$this->_order_mod->table}  " . ($condition?" where ".$condition:'');
        //$total_count = $this->_order_mod->getOne($sql);
        $page = $this->_get_page($perpage);
        $page['item_count'] =$this->_order_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);
        //$this->_assign_order_dedial_info();
        $this->_assign_factory();
        $this->_assign_brand();
        if($_GET['search'] || $_GET['status'] =='1') {
            $this->assign('search', '1');
            $this->assign('get_para', ecm_json_encode($_GET));
        }
        $buyer_mod=&m('member');
    	if ($this->_role==USER_CLIENT){
        	$buyers=$buyer_mod->find(array('conditions'=>'user_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }else{
        	$buyers=$buyer_mod->find(array('conditions'=>'activation=1 and role='.USER_CLIENT));
        }
        $fabric_mod =& m('fabric');
        $this->assign('fabric_list', $fabric_mod->find(array('conditions'=>'if_show = 1', 'order'=>'fabric_name ASC')));
        $feature_mod =& m('feature');
        $this->assign('feature_list', $feature_mod->find(array('conditions'=>'if_show = 1', 'order'=>'feature_name ASC')));
        $this->assign('buyer_list',$buyers);
        if ($this->_role==USER_QC){
        	$qc_list=$buyer_mod->find(array('conditions'=>'user_id='.$this->user['user_id'].' and activation=1 and role='.USER_QC));
        }elseif ($this->_role==USER_FACTORY){
        	$qc_mod=&m('qcfactory');
        	$qc_arr=$qc_mod->find(array('conditions'=>'factory_id='.$user['factory_id']));
        	if (!empty($qc_arr)){
        		foreach ($qc_arr as $val){
        			$qc_arr_id[]=$val['user_id'];
        		}
        	}
        	$qc_list=$buyer_mod->find(array('conditions'=>'user_id'.db_create_in($qc_arr_id).' and activation=1 and role='.USER_QC));
        }else{
        	$qc_list=$buyer_mod->find(array('conditions'=>'activation=1 and role='.USER_QC));
        }
        
        $this->assign('qc_list',$qc_list);
        $sample_mod = &m('sample');
        $sample_sn_list = $sample_mod->find(array('fields'=>'sample_sn,sample_id','order'=>'sample_id ASC'));
        $this->assign('sample_sn',$sample_sn_list);
        $this->assign('fabrics',$this->_order_mod->get_common_data('fabric_shop'));
        $this->assign('styles',$this->_order_mod->get_common_data('style'));
        $this->assign('specials',$this->_order_mod->get_common_data('special'));
        $this->assign('orders',$orders);
        $this->display('order.search.html');
    }
    function status_search() {
        $this->_ican('order_status_search');
        /*$page=$_GET['page']?intval($_GET['page']):'1';
        $perpage=PERPAGE;
        $start=($page-1)*$perpage;
        $start<0 && $start=0;*/

        $condition=$this->_get_conditions();
        //echo $condition;
		$page = $this->_get_page();
        $orders=$this->_order_mod->find(
                array(
                'limit'=>$page['limit'],
                'conditions'=>$condition,
				'count' => true,
                )
        );
        //$sql = "SELECT COUNT(*) FROM {$this->_order_mod->table}  " . ($condition?" where ".$condition:'');
        //$total_count = $this->_order_mod->getOne($sql);
        //$page = $this->_get_page($perpage);
        //$page['item_count'] =$total_count;
		$page['item_count'] = $this->_order_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);
        //$this->_assign_order_dedial_info();
		
        $atttype=array(
			'pigai'=>BELONGS_PIGAI,
			'zhidan'=>BELONGS_ZHIDAN,
			'hetong'=>BELONGS_HETONG,
			'chahuo'=>BELONGS_CHAHUO,
			'zhidan'=>BELONGS_ZHIDAN,
			'koukuan'=>BELONGS_KOUKUAN,
			'caigou'=>BELONGS_CAIGOU
        );
		$file_mod =& m('upload');
		$sample_mod =& m('sample');
		foreach ($orders as $key => $val) {
			/* 查货报告 */
			$orders[$key]['file_pigai'] = $file_mod->find(array(
				'conditions' => 'file_type = ' . BELONGS_PIGAI . ' AND key_id = ' . $val['order_id'],
				'order' => 'file_id ASC',
			));
			$orders[$key]['file_hetong'] = $file_mod->find(array(
				'conditions' => 'file_type = ' . BELONGS_HETONG . ' AND key_id = ' . $val['order_id'],
				'order' => 'file_id ASC',
			));
			$orders[$key]['file_zhidan'] = $file_mod->find(array(
				'conditions' => 'file_type = ' . BELONGS_ZHIDAN . ' AND key_id = ' . $val['order_id'],
				'order' => 'file_id ASC',
			));
			$orders[$key]['file_chahuo'] = $file_mod->find(array(
				'conditions' => 'file_type = ' . BELONGS_CHAHUO . ' AND key_id = ' . $val['order_id'],
				'order' => 'file_id ASC',
			));
			/* 工厂附件 */
			/*$sample = $sample_mod->get(array(
				'conditions' => "sample_sn = '$orders[$key][sample_id]'",
			));*/
			if ($orders[$key]['sample_id']) {
				$orders[$key]['file_factory'] = $file_mod->find(array(
					'conditions' => 'file_type = ' . BELONGS_FACTORY . ' AND key_id = ' . $orders[$key]['sample_id'],
					'order' => 'file_id ASC',
				));
			}
		}
        $this->_assign_common_info();
        if($_GET['search'] || $_GET['status'] =='1') {
            $this->assign('search', '1');
            $this->assign('get_para', ecm_json_encode($_GET));
        }
        $pp_mode=&m('pp');
        foreach($orders as $k=>$v) {
            $orders[$k]['left_days']=$orders[$k]['buyer_arrival_date']?ceil(($orders[$k]['buyer_arrival_date']-TIME)/3600/24):'--';
            $orders[$k]['pp']=$pp_mode->get(
                    array('conditions'=>'order_id='.$v['order_id'],
                    'order'=>'number desc',
                    'limit'=>'1')
            );
        }
        $buyer_mod=&m('member');
    	if ($this->_role==USER_CLIENT){
        	$buyers=$buyer_mod->find(array('conditions'=>'user_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }elseif ($this->_role==USER_MERCHANDISER){
        	$buyers=$buyer_mod->find(array('conditions'=>'freight_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }else{
        	$buyers=$buyer_mod->find(array('conditions'=>'activation=1 and role='.USER_CLIENT));
        }
		$this->assign('atttype', $atttype);
        $this->assign('buyer_list',$buyers);
        $this->assign('orders',$orders);
        $this->display('order.status.search.html');
    }
    function _get_conditions() {
//         if($this->_role==USER_MERCHANDISER) {
//             $user=$this->visitor->get();
//             //print_r($user);
//             $this->assign('merchandiser_list',array($user));
//         }
//         else {
		 if($this->_role==3 || $this->_role==7)
		{
		   /* 获取跟单 */
		$merch_mod =& m('member');
		$merch_list = $merch_mod->find(array(
			'conditions' => 'role = ' . USER_MERCHANDISER . ' AND if_show = 1',
			'order' => 'user_name',
		));
		$this->assign('merchandiser_list', $merch_list);
		}elseif ($this->_role==USER_CLIENT){
			$merch_mod =& m('member');
			$member_info=$merch_mod->get_info($this->visitor->get('user_id'));
			$merchandiser_list=$merch_mod->find(array(
					'conditions'=>'user_id='.$member_info['freight_id'].' and role='.USER_MERCHANDISER.' and if_show=1'
			));
			$this->assign('merchandiser_list', $merchandiser_list);
		}
		else
		{
			
            $user=&m('member')->find(array('conditions'=>'role='.USER_MERCHANDISER.' AND if_show = 1'));
            //print_r($user);
            $this->assign('merchandiser_list',$user);
		}
			
			
			
//         }

			if($_GET['status'] =='-1') {
			}
			elseif(isset($_GET['status'])) {
				$conditions[]=" `status`='".intval($_GET['status'])."' ";
			}
		  else {

		  }
		
        if($_GET['order_create_date']) {
            $conditions[]=" order_create_date >='".strtotime($_GET['order_create_date'])."' ";
        }
        if($_GET['order_create_date2']) {
            $conditions[]=" order_create_date <='".strtotime($_GET['order_create_date2'])."' ";
        }
        if($_GET['order_sn']) {
            $conditions[]=" `order_sn` like '%".$_GET['order_sn']."%' ";
        }
        if($_GET['style_sn']) {
            $conditions[]=" `style_sn` like '%".$_GET['style_sn']."%' ";
        }
        if($_GET['buyer_id']) {
            $conditions[]=" `buyer_id`='".intval($_GET['buyer_id'])."' ";
        }
        if($_GET['brand_id']) {
            $conditions[]=" `brand_id`='".intval($_GET['brand_id'])."' ";
        }
        if($_GET['style_id']) {
            $conditions[]=" `style_id`='".intval($_GET['style_id'])."' ";
        }
        if($_GET['special_id']) {
            $conditions[]=" `special_id`='".intval($_GET['special_id'])."' ";
        }
		if($_GET['dis_status']) {
			$conditions[]=" `dis_status`='".intval($_GET['dis_status'])."' ";
		}
        if($_GET['feature_id']) {
            $conditions[]=" `feature_id`='".intval($_GET['feature_id'])."' ";
        }
        if($_GET['fabric_id']) {
            $conditions[]=" `fabric_id`='".intval($_GET['fabric_id'])."' ";
        }
        if($_GET['factory_id']) {
            $conditions[]=" `factory_id`='".intval($_GET['factory_id'])."' ";
        }
        if($_GET['product_status'] =='-1') {
        }elseif($_GET['product_status']) {
        	$conditions[]=" `product_status`='".intval($_GET['product_status'])."' ";
        }
        if($_GET['merchandiser_id']>0) {
            $conditions[]=" `merchandiser_id`='".intval($_GET['merchandiser_id'])."' ";
        }
        elseif($this->_role==USER_MERCHANDISER && $_GET['merchandiser_id']>0) {
        	$conditions[]=" `merchandiser_id`='".$user['user_id']."' ";
            //echo " `merchandiser_id`='".$user['user_id']."' ";
        }
        if($_GET['release_date']) {
            $conditions[]=" `release_date`>='".strtotime($_GET['release_date'])."' ";
            if (ACT=='reconlist'){
            	$this->assign('release_date_start',strtotime($_GET['release_date']));
            }
        }
        if($_GET['release_date2']) {
            $conditions[]=" `release_date`<='".strtotime($_GET['release_date2'])."' ";
            if (ACT=='reconlist'){
            	$this->assign('release_date_end',strtotime($_GET['release_date2']));
            }
        }
        if($_GET['task']>0) {
            if($_GET['task']=='7days') {
                $weekday=date('N');
                $conditions[]=" `buyer_arrival_date`>='".(TIME-$weekday*3600*24)."' and `buyer_arrival_date`<=".(TIME+(7-$weekday)*3600*24)."";
            }
        }

        $condition=$conditions?join(' and ',$conditions):'';
        return $condition;
    }
	
	function ajax_edit()
	{
		if (IS_POST) {
			$id = $_GET['id'];
			if (!$id) {
				echo ecm_json_encode(array('done' => false,'msg' => '找不到订单'));
				return;
			}
			$field = trim($_POST['field']);
			$value = trim($_POST['value']);
			//if (!$field || !$value) {
			if (!$field) {
				echo ecm_json_encode(array('done'=>false,'msg'=>'参数错误22'));
				return;
			}
			$data[$field] = $value;
			$this->_order_mod->edit($id, $data);
			if ($this->_order_mod->get_error()) {
				echo ecm_json_encode(array('done'=>false,'msg'=>$this->_order->get_error()));
				return;
			}
			echo ecm_json_encode(array('done'=>true,'msg'=>'更新成功'));
			
		}
	}
	
	function init_order()
	{
		$id = intval($_GET['id']);
		if (!$id) {
			echo ecm_json_encode(array('done'=>false,'msg'=>'参数错误！'));
			return;
		}
		$this->_order_mod->edit($id, array(
			'status' => 1,
			'confirm_date' => 0,
		));
		echo ecm_json_encode(array('done'=>false,'msg'=>'初始化订单成功！'));
	}
	
	//增加进度记录
	function addrecord()
	{
		$buff=isset($_GET['buff'])?trim($_GET['buff']):'';
		$id=isset($_GET['id'])?intval($_GET['id']):0;
		if(!empty($buff)&&!empty($id))
		{
			$mod_pro_records=&m("pro_records");
			$data=array(
				"type"=>PRO_RECORDS_ORDER,
				"key_id"=>$id,
				"rec_name"=>$this->visitor->get("user_name"),
				"rec_buff"=>$buff,
				"rec_time"=>gmtime()				
			);
			if(!$mod_pro_records->add($data))
			{
			   $this->json_error($mod_pro_records->get_error());

			}
			else
			{
				$rec_time=gmtimeshow($data['rec_time'],"m-d");
			   $this->json_result("<p>{$rec_time}&nbsp;:&nbsp;{$buff}&nbsp;&nbsp;({$data['rec_name']})</p>");
			}
		}
	}
	
	
	//待审批订单
	function approve()
	{
		
		 $this->_ican('view_order_list');
        $page=$_GET['page']?intval($_GET['page']):'1';
        $perpage=PERPAGE;
        $start=($page-1)*$perpage;
        $start<0 && $start=0;
       
	   $this->_curlocal("待审批订单");
	   
		$this->_get_conditions();//只借用原来的赋值
		
        $condition=$this->_get_query_conditions(array(
            array(      
                'field' => 'order_sn',
                'name'  => 'order_sn',
                'equal' => 'LIKE',
				'type'  => 'string'
            ),
            array(    
                'field' => 'style_sn',
				'name'  => 'style_sn',
                'equal' => 'LIKE',
				'type'  => 'string'
            ),
            array(      
                'field' => 'factory_id',
                'name'  => 'factory_id',
                'equal' => '=',
				'type'  => 'numeric'
            ),
            array(      
                'field' => 'brand_id',
                'name'  => 'brand_id',
                'equal' => '=',
				'type'  => 'numeric'
            ),
			array(      
                'field' => 'buyer_id',
                'name'  => 'buyer_id',
                'equal' => '=',
				'type'  => 'numeric'
            ),
			array(      
                'field' => 'merchandiser_id',
                'name'  => 'merchandiser_id',
                'equal' => '=',
				'type'  => 'numeric'
            ),
        ));
        $user = $this->visitor->get();
        $this->assign("user",$user);
		if(empty($_GET['factory_id'])&&$user[role]==USER_QC){
			$qf_re = $this->qc_factory_info($user);
			$condition .= ' AND '.$qf_re;
		}
		if(empty($_GET['factory_id'])&&$user[role]==USER_OUTGOING){
			//$condition .=" and 1=1";
			$qf_re = $this->qc_factory_info();
			$condition .= ' AND '.$qf_re;
		}

		if ($user['role'] == USER_MANAGER) {
			$conditions[] = "o.status in(".ORDER_STATUS_APPROVE.",".ORDER_STATUS_APPROVE_MANAGER.")";
		} elseif ($user['role'] == USER_FINANCE) {
			$conditions[] = "o.status in(".ORDER_STATUS_APPROVE.",".ORDER_STATUS_APPROVE_FINANCE.")";
		} elseif ($user['role'] == USER_MERCHANDISER_ADMIN){
			$conditions[] = "o.status in(".ORDER_STATUS_APPROVE.",".ORDER_STATUS_APPROVE_MANAGER.")";
			$mod_company_manager=&m("company_manager");
			$brand_mod =& m('brand');
			$conditions[]="o.brand_id in(select brand_id from {$brand_mod->table} where company_id in(select company_id from {$mod_company_manager->table} where uid={$this->visitor->get('user_id')}))";
		}else {
			$conditions[] = "o.status=-100";
		}
		
		$conditions =  implode(' AND ', $conditions);

		   $condition = $condition . " AND ".$conditions;

        $page = $this->_get_page();
		
		$order = empty($_GET['order']) ? 'order_create_date DESC' : str_replace('-', ' ', trim($_GET['order']));
		if ($order != 'order_create_date DESC' || $order != 'order_create_date ASC') {
			$order .= ', order_create_date DESC';
		}
		
		
        $orders=$this->_order_mod->find(
                array(
                'conditions'=>"1=1 ".$condition,
                    'count' => true,
                    'limit' => $page['limit'],
					'order' => $order.',style_sn desc'
                )
        );

        $page['item_count'] = $this->_order_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);

		
        $this->_assign_common_info();
        if($_GET['search'] || $_GET['status'] =='1') {
            $this->assign('search', '1');
            $this->assign('get_para', ecm_json_encode($_GET));
        }
        $buyer_mod=&m('member');
		if ($this->_role==USER_CLIENT){
        	$buyers=$buyer_mod->find(array('conditions'=>'user_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }elseif ($this->_role==USER_MERCHANDISER){
        	$buyers=$buyer_mod->find(array('conditions'=>'freight_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }else{
        	$buyers=$buyer_mod->find(array('conditions'=>'activation=1 and role='.USER_CLIENT));
        }
        $this->assign('buyer_list',$buyers);
        $this->assign('orders',$orders);
		if ($this->visitor->get('role') == USER_MANAGER) {
			$this->assign('manager', USER_MANAGER);
		}
        $this->display('order.approve.html');
	}
	
	
	//检查订单是否能被哪种角色编辑
	function _check_order_is_edit($order)
	{
		
		$role=$this->visitor->get('role');
		$merch_ids = explode(',', $this->visitor->get('merchandiser'));
		switch($order['status'])
		{
			case ORDER_STATUS_NO_CONFIRM:		//未确认
			   if (($role==USER_ASSISTANT&&!in_array($order['merchandiser_id'], $merch_ids))||($role==USER_MERCHANDISER&&$order['merchandiser_id'] != $this->visitor->get('user_id'))||!in_array($role,array(USER_ASSISTANT,USER_MERCHANDISER,USER_MERCHANDISER_ADMIN,USER_MANAGER,USER_OUTGOING))) {
				  return false;
			  }
			break;
			case ORDER_STATUS_APPROVE:		//待审批
			  if (($role==USER_ASSISTANT&&!in_array($order['merchandiser_id'], $merch_ids))||($role==USER_MERCHANDISER&&$order['merchandiser_id'] != $this->visitor->get('user_id'))||!in_array($role,array(USER_ASSISTANT,USER_MERCHANDISER,USER_MERCHANDISER_ADMIN,USER_MANAGER,USER_OUTGOING))) {
				  return true;
			  }
			break;
			case ORDER_STATUS_APPROVE_MANAGER:		//主管审批
			  if (($role==USER_ASSISTANT&&!in_array($order['merchandiser_id'], $merch_ids))||($role==USER_MERCHANDISER&&$order['merchandiser_id'] != $this->visitor->get('user_id'))||!in_array($role,array(USER_ASSISTANT,USER_MERCHANDISER,USER_MERCHANDISER_ADMIN,USER_MANAGER))) {
				  return false;
			  }
			break;
			case ORDER_STATUS_APPROVE_FINANCE:		//财务审批
			  if (($role==USER_ASSISTANT&&!in_array($order['merchandiser_id'], $merch_ids))||($role==USER_MERCHANDISER&&$order['merchandiser_id'] != $this->visitor->get('user_id'))||!in_array($role,array(USER_ASSISTANT,USER_MERCHANDISER,USER_MERCHANDISER_ADMIN,USER_MANAGER,USER_FINANCE))) {
				  return false;
			  }
			break;
			case ORDER_STATUS_FACTORY_CONFIRM:		//工厂确认
			if (($role==USER_ASSISTANT&&!in_array($order['merchandiser_id'], $merch_ids))||($role==USER_MERCHANDISER&&$order['merchandiser_id'] != $this->visitor->get('user_id'))||($role==USER_FACTORY&&$order['factory_id'] != $this->visitor->get('factory_id')) || !in_array($role,array(USER_ASSISTANT,USER_MERCHANDISER,USER_MERCHANDISER_ADMIN,USER_MANAGER))) {
				  return false;
			  }
			break;
			case ORDER_STATUS_CONFIRM:		//已确认
			   if (($role==USER_ASSISTANT&&!in_array($order['merchandiser_id'], $merch_ids))||($role==USER_MERCHANDISER&&$order['merchandiser_id'] != $this->visitor->get('user_id'))||!in_array($role,array(USER_ASSISTANT,USER_MERCHANDISER,USER_MERCHANDISER_ADMIN,USER_MANAGER,USER_QC))) {
				  return false;
			  }
			break;
			case ORDER_STATUS_NO_CANCEL:		//已取消
			   if (($role==USER_ASSISTANT&&!in_array($order['merchandiser_id'], $merch_ids))||($role==USER_MERCHANDISER&&$order['merchandiser_id'] != $this->visitor->get('user_id'))||!in_array($role,array(USER_ASSISTANT,USER_MERCHANDISER,USER_MERCHANDISER_ADMIN,USER_MANAGER))) {
				  return false;
			  }
			break;
			default:				//其他
			
			return false;
			
		}
		return true;
	}
	
	//打印订单
	function order_print()
	{
		$id=$_GET['id']?intval($_GET['id']):0;
        if(!$id) {
            $this->show_warning('请选择订单');
			return;
        }
        $order=$this->_order_mod->get($id);
        if(!$order) {
            $this->show_warning('订单不存在');
			return;
        }
		
		if($this->visitor->get("role")==USER_FACTORY&&$order['factory_id']!=$this->visitor->get("factory_id"))
		{
			$this->show_warning('用户无权限操作此订单');
			return;
		}
		
		//限制那些状态只能哪些角色编辑
		$is_edit=$this->_check_order_is_edit($order);
		$this->assign("is_edit",$is_edit);
		
		//添加一个限制条件  
		$factory_role=$this->visitor->get('role');
		if($factory_role == USER_FACTORY and $order['status'] == ORDER_STATUS_FACTORY_CONFIRM){
			//$this->assign('factory_role',true);
		}
		$file_mod=&m('upload');
		$user_info=$this->visitor->get();
		$this->assign('user', $user_info);
		
		//获取对应的制单信息
		$ss_mod =& m('ss');
		$ss_info=$ss_mod->get("order_id={$id}");
		$this->assign("ss_info",$ss_info);
			//赋值进度记录
			$mod_pro_records=&m("pro_records");
			$pro_records_list=$mod_pro_records->find(array(
				'conditions'=>"key_id={$id} AND type=".PRO_RECORDS_ORDER,
				'order'	=>"rec_time desc"
			));
			$this->assign("pro_records_list",$pro_records_list);
			
			//赋值色卡信息
			$colorcard_mode=& m('color_card');
			
			$fabric_shop_list=$colorcard_mode->getall("select fabric_shop_name,fabric_shop_id from {$colorcard_mode->table} group by fabric_shop_id order by fabric_shop_name,update_time desc");

			$this->assign("fabric_shop_list",$fabric_shop_list);
			
			$brand_mod =& m('brand');
			$this->assign('brand_list', $brand_mod->find(array('conditions'=>'if_show=1','join'=>"belong_company",'order'=>'brand_name ASC')));
			$brand_info=$brand_mod->get($order['brand_id']);
			$company_id=!empty($brand_info)?$brand_info['company_id']:0;
			
			$buyer_mod =& m('member');
			$this->assign('buyer_list', $buyer_mod->find(array('conditions'=>'if_show=1 and activation=1 and role='.USER_CLIENT)));
			
			$user_mod =& m('member');
			$this->assign('merchandiser_list', $user_mod->find(array('conditions'=>'if_show=1 AND role='.USER_MERCHANDISER.' AND user_id='.$order['merchandiser_id'])));
			$disreason_type_mod =& m('disreason_type');
			$this->assign('disreason_type_list', $disreason_type_mod->find(array('conditions'=>"1=1")));

			
			$sample_mod =& m('sample');
			$this->assign('sample_list', $sample_mod->find(array('order'=>'sample_sn ASC')));
			
			$style_mod =& m('style');
			$this->assign('style_list', $style_mod->find(array('conditions'=>'if_show=1','order'=>'style_name DESC')));
			
			$factory_mod =& m('factory_info');
			$this->assign('factory_list', $factory_mod->find(array('conditions'=>'if_show = 1 and activation=1', 'order'=>'factory_name', 'join'=>'belongs_factory_member')));
		
			$fs_mod =& m('fabric_shop');
			$this->assign('fabricshop_list', $fs_mod->find(array('conditions'=>'if_show=1','order'=>'fabric_shop_name ASC')));
			
			//qc列表
// 			if (in_array($user_info['role'], array(USER_QC,USER_OUTGOING))){
// 				$qc_list=$user_mod->find(array(
// 						'conditions'=>'if_show=1 and role='.USER_QC,
// 						'order'=>'user_name asc'
// 				));
// 				$this->assign('qc_list',$qc_list);
// 				$qc_factory_mod=&m('qcfactory');
// 				$qf=$qc_factory_mod->get("order_id=".$id);
// 				if (!empty($qf)){
// 					$this->assign('qf',$qf['user_id']);
// 				}
// 			}
			
			$quote_mod=& m('quote');
			$page = $this->_get_page(10);
			if (in_array($user_info['role'], array(USER_MANAGER,USER_MERCHANDISER,USER_MERCHANDISER_ADMIN,USER_FINANCE))){
				//获取加工工厂的报价信息
				$file_mod=&m('upload');
				$quote_list=$quote_mod->find(array(
						'join'=>'belongs_factory',
						'conditions'=>'order_id='.$id,
						'count'=>true,
						'limit'=>$page['limit']
				));
				if (!empty($quote_list)){
					foreach ($quote_list as $key=>$rows){
						$f_id=$rows['factory_id'];
						$quote_list[$key]['order_num']=$quote_mod->getOne("select sum(order_num) from {$quote_mod->table} where if_option=1 and factory_id=".$f_id);
						$quote_list[$key]['file_quote']=$file_mod->find(array('conditions'=>'file_type = '.BELONGS_QUOTE_ORDER.' AND key_id = '.$rows['quote_id'],'order'=>'file_id ASC'));
					}
				}
				$page['item_count'] = $quote_mod->getCount();
				/* 报价附件 */
				$this->assign('belongs_quote_order', BELONGS_QUOTE_ORDER);
				$this->assign('quote_list',$quote_list);
			}
			
			$this->_assign_files($order['order_id'], $order['sample_id']);
			$this->assign('order', $order);
			$this->assign('role', $this->visitor->get('role'));
			$this->assign('page_title', '订单信息');
            $this->display('order.print.html');
	}
	
		
	//待审批制单
	function ssapprove()
	{
		  $page=$_GET['page']?intval($_GET['page']):'1';
        $perpage=PERPAGE;
        $start=($page-1)*$perpage;
        $start<0 && $start=0;
       
	   $this->_curlocal("待审批制单");
	   
		$this->_get_conditions();//只借用原来的赋值
		
        $condition=$this->_get_query_conditions(array(
            array(      
                'field' => 'order_sn',
                'name'  => 'order_sn',
                'equal' => 'LIKE',
				'type'  => 'string'
            ),
            array(    
                'field' => 'style_sn',
				'name'  => 'style_sn',
                'equal' => 'LIKE',
				'type'  => 'string'
            ),
            array(      
                'field' => 'factory_id',
                'name'  => 'factory_id',
                'equal' => '=',
				'type'  => 'numeric'
            ),
            array(      
                'field' => 'brand_id',
                'name'  => 'brand_id',
                'equal' => '=',
				'type'  => 'numeric'
            ),
			array(      
                'field' => 'buyer_id',
                'name'  => 'buyer_id',
                'equal' => '=',
				'type'  => 'numeric'
            ),
			array(      
                'field' => 'merchandiser_id',
                'name'  => 'merchandiser_id',
                'equal' => '=',
				'type'  => 'numeric'
            ),
        ));
		
		$user = $this->visitor->get();
		$this->assign("user",$user);
		
		$conditions[] = "ss.ss_status =".SS_STATUS_APPROVE;
		if ($user['role'] == USER_MERCHANDISER_ADMIN) {
			$mod_company_manager=&m("company_manager");
			$brand_mod =& m('brand');
			$conditions[]="o.brand_id in(select brand_id from {$brand_mod->table} where company_id in(select company_id from {$mod_company_manager->table} where uid={$this->visitor->get('user_id')}))";
		}
		$conditions =  implode(' AND ', $conditions);

		$condition = $condition . " AND ".$conditions;

        $page = $this->_get_page();
		
		$order = empty($_GET['order']) ? 'order_create_date DESC' : str_replace('-', ' ', trim($_GET['order']));
		if ($order != 'order_create_date DESC' || $order != 'order_create_date ASC') {
			$order .= ', order_create_date DESC';
		}
		
		
        $orders=$this->_order_mod->find(
                array(
                'conditions'=>"1=1 ".$condition,
                    'count' => true,
					'join'	=>"has_ss",
                    'limit' => $page['limit'],
					'order' => $order.',style_sn desc'
                )
        );
		
        if ($user['role']!=USER_CLIENT){
        	$ss_mod=& m('ss');
        	if (!empty($orders)){
        		foreach ($orders as $key=>$rows){
        			$order_id=$rows['order_id'];
        			$ss_list=$ss_mod->get("order_id=".$order_id);
        			$orders[$key]['ss_id']=$ss_list['ss_id'];
        			$orders[$key]['ss_status']=$ss_list['ss_status'];
        		}
        	}
        }
        $page['item_count'] = $this->_order_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);

		
        $this->_assign_common_info();
        if($_GET['search'] || $_GET['status'] =='1') {
            $this->assign('search', '1');
            $this->assign('get_para', ecm_json_encode($_GET));
        }
        $buyer_mod=&m('member');
		if ($this->_role==USER_CLIENT){
        	$buyers=$buyer_mod->find(array('conditions'=>'user_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }elseif ($this->_role==USER_MERCHANDISER){
        	$buyers=$buyer_mod->find(array('conditions'=>'freight_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }else{
        	$buyers=$buyer_mod->find(array('conditions'=>'activation=1 and role='.USER_CLIENT));
        }
        $this->assign('buyer_list',$buyers);
        $this->assign('orders',$orders);
		if ($this->visitor->get('role') == USER_MANAGER) {
			$this->assign('manager', USER_MANAGER);
		}
		
        $this->display('order.ssapprove.html');
	}
	
		//已审批制单
	function ssapproved()
	{
		  $page=$_GET['page']?intval($_GET['page']):'1';
        $perpage=PERPAGE;
        $start=($page-1)*$perpage;
        $start<0 && $start=0;
       
	   $this->_curlocal("已审批制单");
	   
		$this->_get_conditions();//只借用原来的赋值
		
        $condition=$this->_get_query_conditions(array(
            array(      
                'field' => 'order_sn',
                'name'  => 'order_sn',
                'equal' => 'LIKE',
				'type'  => 'string'
            ),
            array(    
                'field' => 'style_sn',
				'name'  => 'style_sn',
                'equal' => 'LIKE',
				'type'  => 'string'
            ),
            array(      
                'field' => 'factory_id',
                'name'  => 'factory_id',
                'equal' => '=',
				'type'  => 'numeric'
            ),
            array(      
                'field' => 'brand_id',
                'name'  => 'brand_id',
                'equal' => '=',
				'type'  => 'numeric'
            ),
			array(      
                'field' => 'buyer_id',
                'name'  => 'buyer_id',
                'equal' => '=',
				'type'  => 'numeric'
            ),
			array(      
                'field' => 'merchandiser_id',
                'name'  => 'merchandiser_id',
                'equal' => '=',
				'type'  => 'numeric'
            ),
        ));
		
		$user = $this->visitor->get();
		$this->assign("user",$user);
		$condition .=" and pass_status=0";
		if(empty($_GET['factory_id'])&&$user[role]==USER_QC){
			$qf_re = $this->qc_factory_info($user);
			$condition .= ' AND '.$qf_re;
		}
		if(empty($_GET['factory_id'])&&$user[role]==USER_OUTGOING){
			//$condition.=" and 1=1";
			$qf_re = $this->qc_factory_info();
			$condition .= ' AND '.$qf_re;
		}
		if ($user['role'] == USER_MERCHANDISER_ADMIN) {
			$mod_company_manager=&m("company_manager");
			$brand_mod =& m('brand');
			$conditions[]="o.brand_id in(select brand_id from {$brand_mod->table} where company_id in(select company_id from {$mod_company_manager->table} where uid={$this->visitor->get('user_id')}))";
		}
		$conditions[] = "ss.ss_status =".SS_STATUS_SUCCESS;
		
		$conditions =  implode(' AND ', $conditions);

		$condition = $condition . " AND ".$conditions;

        $page = $this->_get_page();
		
		$order = empty($_GET['order']) ? 'order_create_date DESC' : str_replace('-', ' ', trim($_GET['order']));
		if ($order != 'order_create_date DESC' || $order != 'order_create_date ASC') {
			$order .= ', order_create_date DESC';
		}
		
		
        $orders=$this->_order_mod->find(
                array(
                'conditions'=>"1=1 ".$condition,
                    'count' => true,
					'join'	=>"has_ss",
                    'limit' => $page['limit'],
					'order' => $order.',style_sn desc'
                )
        );
		

        $page['item_count'] = $this->_order_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);

		
        $this->_assign_common_info();
        if($_GET['search'] || $_GET['status'] =='1') {
            $this->assign('search', '1');
            $this->assign('get_para', ecm_json_encode($_GET));
        }
        $buyer_mod=&m('member');
		if ($this->_role==USER_CLIENT){
        	$buyers=$buyer_mod->find(array('conditions'=>'user_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }elseif ($this->_role==USER_MERCHANDISER){
        	$buyers=$buyer_mod->find(array('conditions'=>'freight_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }else{
        	$buyers=$buyer_mod->find(array('conditions'=>'activation=1 and role='.USER_CLIENT));
        }
        $this->assign('buyer_list',$buyers);
        $this->assign('orders',$orders);
		if ($this->visitor->get('role') == USER_MANAGER) {
			$this->assign('manager', USER_MANAGER);
		}
		
        $this->display('order.ssapprove.html');
	}
	
	
	//通知档口
	function pass_merchant(){
		$ss_id = $_REQUEST['ss_id']?intval($_REQUEST['ss_id']):'0';
		if(!$ss_id){
			$this->show_warning('错误，通知出错','返回已审批制单列表','index.php?app=order&act=order_ssapproved');
			return;
		}
		$ss_mod=&m('single_system');
		$ss_info = $ss_mod->get_info($ss_id);
		
		if($ss_info['ss_status']!=SS_STATUS_SUCCESS || $ss_info['pass_status']!=0)
		{
			$this->show_warning("操作错误",'返回已审批制单列表',"index.php?app=order&act=order_ssapproved");
			return;
		}
		$order=$this->_order_mod->get($ss_info['order_id']);
		$data['pass_status']=1;
		$fabric_info_mod =& m('fabric_info');
		$fabric_info_list = $fabric_info_mod->find(array(
				'conditions'=>'ss_id='.$ss_id,
				'fields'=>"fabric_info.fabric_info_id,user_id,fabric_shop_name,item",
				'join'	=>"belongs_fabric_shop",
				'order'=>'fabric_info_id ASC'
		));
		$ss_mod->edit($ss_id,$data);
		if ($ss_mod->has_error()){
			$this->show_warning($ss_mod->get_error());
			return ;
		}
		$merch_info=array();
		$merch_info['order_sn']=$order['order_sn'];
		$merch_info['style_sn']=$order['style_sn'];
		$merch_info['style_name']=$order['style_name'];
		$merch_info['quantity']=$order['quantity'];
		$merch_info['factory_name']=$order['factory_name'];
		if (!empty($fabric_info_list)){
			foreach ($fabric_info_list as $rows){
				$merch_info['fabric_shop_name']=$rows['fabric_shop_name'];
				$merch_info['item']=$rows['item'];
				$mail = get_mail('ss_pass_merchant', array('order' => $merch_info));
				$user_id=$rows['user_id'];
				$uinfo=&m('member')->get($user_id);
				$this->_mailto($uinfo['email'], addslashes($mail['subject']), addslashes($mail['message']));
				$this->_mailto(DEFAULT_MERCH_SEND_EMAIL, addslashes($mail['subject']), addslashes($mail['message']));
			}
		}
		$this->show_message('通知档口成功！');
	}
	
	//已确认订单
	function shipment()
	{
		$this->assign('user_manager',USER_MANAGER);
		$this->assign('user_merch',USER_MERCHANDISER);
		$this->assign('user_merch_admin',USER_MERCHANDISER_ADMIN);
		$this->assign('user_factory',USER_FACTORY);
		$this->assign('user_qc',USER_QC);
		$this->assign('user_outgoing',USER_OUTGOING);
		
		$this->_ican('view_order_list');
        $page=$_GET['page']?intval($_GET['page']):'1';
        $perpage=PERPAGE;
        $start=($page-1)*$perpage;
        $start<0 && $start=0;
       
	   $this->_curlocal("已确认订单");
		
        $condition=$this->_get_conditions();
		
		//显示已确认的所有订单
		$status_str="status =".ORDER_STATUS_CONFIRM;

		$condition.=!empty($condition)?" AND {$status_str}":$status_str;
		
		$user = $this->visitor->get();
		$this->assign("user",$user);
		$buyer_mod=&m('member');
		if (!in_array($user['role'], array(USER_CLIENT,USER_FACTORY,USER_MERCHANT))){
			$this->assign('is_into',true);
			$qc_list=$buyer_mod->find(array(
				'conditions'=>'if_show=1 and role '.db_create_in(array(USER_QC,USER_OUTGOING)),
				'order'=>'user_name desc',
				'fields'=>'user_name'	
			));
			$this->assign('qc_list',$qc_list);
		}
		if ($user['role'] == USER_MERCHANDISER_ADMIN) {
//			$this->assign('user_manage', USER_MANAGER);
//			$merch_id = empty($_GET['merch_id']) ? 0 : intval($_GET['merch_id']);
//			if ($merch_id) {
//				$conditions[] = "merchandiser_id = $merch_id";
//			}
		    $mod_company_manager=&m("company_manager");
			$brand_mod =& m('brand');
			$conditions[]="o.brand_id in(select brand_id from {$brand_mod->table} where company_id in(select company_id from {$mod_company_manager->table} where uid={$this->visitor->get('user_id')}))";
		} elseif ($user['role'] == USER_ASSISTANT) {
			$merch_id = empty($_GET['merch_id']) ? 0 : intval($_GET['merch_id']);
			$this->assign('user_assistant', USER_ASSISTANT);
			$merch_ids = $user['user_id'];
			if ($merch_id) {
				$conditions[] = "merchandiser_id = $merch_id";
			} else {
				$conditions[] = "merchandiser_id in ($merch_ids)";
			}
		}elseif ($user['role']==USER_MANAGER){
			$conditions[]="1=1";
		}
		elseif ($user['role'] == USER_FACTORY) {
			if (!$user['factory_id']){
				$this->show_warning('没有该工厂,如有疑问,请联系管理员');
				return;
			}
			$conditions[] = "factory_id = {$this->visitor->get('factory_id')}";
		}elseif($user['role']== USER_QC){
			$conditions[] = $this->qc_factory_info($user);
		}elseif ($user['role']==USER_CLIENT){
			$merch_id = $user['user_id'];
			$conditions[] = "buyer_id = $merch_id";
		}elseif ($user['role']==USER_OUTGOING){
			//$conditions[]="1=1";
			$conditions[] = $this->qc_factory_info();
		}elseif ($user['role']==USER_CHUANWU){
			$conditions[]="1=1";
		}
		else {
			$merch_id = $user['user_id'];
			$conditions[] = "merchandiser_id = $merch_id";
		}
		if ($_GET['qc_id']){
			$q_id=$_GET['qc_id'];
			$qf_mod = & m('qcfactory');
			$qf_list = $qf_mod->find(array(
					'fields' => 'factory_id',
					'conditions' => 'user_id='.$q_id
			));
			$arr_info = '';
			if($qf_list){
				$arr = array();
				foreach($qf_list as $key=>$value){
					$arr[$key] = $value['factory_id'];
				}
				$arr_info = implode(",",array_unique($arr));
			}
			if(empty($arr_info)){
				$conditions[]="o.factory_id = -1";
			}else{
				$conditions[]="o.factory_id in(".$arr_info.")";
			}
		}
		$conditions = ($condition ? ' AND ' : '') . implode(' AND ', $conditions);

		$condition .= $conditions;
        $page = $this->_get_page();
		$order = empty($_GET['order']) ? 'order_create_date DESC' : str_replace('-', ' ', trim($_GET['order']));
		if ($order != 'order_create_date DESC' || $order != 'order_create_date ASC') {
			$order .= ', order_create_date DESC';
		}
        $orders=$this->_order_mod->find(
                array(
                'conditions'=>$condition,
                    'count' => true,
                    'limit' => $page['limit'],
					'order' => $order.',style_sn desc'
                )
        );
        $page['item_count'] = $this->_order_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);
		
        $this->_assign_common_info();
        if($_GET['search'] || $_GET['status'] =='1') {
            $this->assign('search', '1');
            $this->assign('get_para', ecm_json_encode($_GET));
        }
		if ($this->_role==USER_CLIENT){
        	$buyers=$buyer_mod->find(array('conditions'=>'user_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }elseif ($this->_role==USER_MERCHANDISER){
        	$buyers=$buyer_mod->find(array('conditions'=>'freight_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }else{
        	$buyers=$buyer_mod->find(array('conditions'=>'activation=1 and role='.USER_CLIENT));
        }
        if ($user['role']!=USER_CLIENT){
        	$ss_mod=& m('ss');
        	if (!empty($orders)){
        		$process_mod=& m('qc_process');
        		foreach ($orders as $key=>$rows){
        			$order_id=$rows['order_id'];
        			$ss_list=$ss_mod->get("order_id=".$order_id);
        			$orders[$key]['ss_id']=$ss_list['ss_id'];
        			$orders[$key]['ss_status']=$ss_list['ss_status'];
        			$process_list=$process_mod->find(array(
        				'conditions'=>'qc_process.order_id='.$order_id,
        				'join'=>'belongs_process_order',
        				'order'=>'receipt_time desc',
        				'limit'=>5	
        			));
        			if (!empty($process_list)){
        				foreach ($process_list as $k=>$v){
        					$qc_id=$v['qc_id'];
        					$qc_info=$buyer_mod->get(array(
        						'conditions'=>'user_id='.$qc_id.' and role='.USER_QC,
        						'fields'=>'user_name'	
        					));
        					$process_list[$k]['qc_name']=$qc_info['user_name'];
        				}
        			}
        			$orders[$key]['process_list']=$process_list;
        		}
        	}
        }
        $this->assign('buyer_list',$buyers);
        $this->assign('orders',$orders);
		if ($this->visitor->get('role') == USER_MANAGER) {
			$this->assign('manager', USER_MANAGER);
		}
        $this->display('order.shipment.html');
	}
	
	//获取qc与工厂关系信息
	function qc_factory_info($user=array()){
		$qf_mod = & m('qcfactory');
		if ($user){
			$qf_list = $qf_mod->find(array(
					'fields' => 'factory_id',
					'conditions' => 'user_id='.$user['user_id']
			));
		}else{
			$user_mod=&m('member');
			$user_list=$user_mod->find(array(
				'fields'=>'user_id',
				'conditions'=>'role'.db_create_in(array(USER_QC,USER_OUTGOING))	
			));
			if (!empty($user_list)){
				$user_arr_id=array();
				foreach ($user_list as $rows){
					$user_arr_id[]=$rows['user_id'];
				}
				$qf_list=$qf_mod->find(array(
						'fields'=>'factory_id',
						'conditions'=>'user_id '.db_create_in($user_arr_id)
				));
			}
		}
		$arr_info = '';
		if($qf_list){
			$arr = array();
			foreach($qf_list as $key=>$value){
				$arr[$key] = $value['factory_id'];
			}
			$arr_info = implode(",",array_unique($arr));
		}
		if(empty($arr_info)){
			return "o.factory_id = -1";
		}else{
			return "o.factory_id in(".$arr_info.")";
		}
	}
	
	//订单统计
	function statistics()
	{
		$this->_curlocal("订单统计");
		$this->display('order.statistics.html');
	}
	
	//大货折扣
	function cargo_discount()
	{
        $page=$_GET['page']?intval($_GET['page']):'1';
        $perpage=PERPAGE;
        $start=($page-1)*$perpage;
        $start<0 && $start=0;
		
        $condition=$this->_get_conditions();
        $user = $this->visitor->get();
		//显示已确认前的所有订单
		$status_str="dis_status !=".ORDER_DIS_STATUS_NO;
// 		if ($user['role']==USER_FINANCE){
// 			$status_str="dis_status=".ORDER_DIS_STATUS_APPROVE_FINANCE;
// 		}
		$condition.=!empty($condition)?" AND {$status_str}":$status_str;
		$this->assign("user",$user);
		if ($user['role'] == USER_MANAGER) {
			$this->assign('user_manage', USER_MANAGER);
			$merch_id = empty($_GET['merch_id']) ? 0 : intval($_GET['merch_id']);
			if ($merch_id) {
				$conditions[] = "merchandiser_id = $merch_id";
			}
		} elseif ($user['role'] == USER_ASSISTANT) {
			$merch_id = empty($_GET['merch_id']) ? 0 : intval($_GET['merch_id']);
			$this->assign('user_assistant', USER_ASSISTANT);
			$merch_ids = $user['merchandiser'];
			if ($merch_id) {
				$conditions[] = "merchandiser_id = $merch_id";
			} else {
				$conditions[] = "merchandiser_id in ($merch_ids)";
			}
		} 
		elseif ($user['role'] == USER_FACTORY) {
			if (!$user['factory_id']){
				$this->show_warning('没有该工厂,如有疑问,请联系管理员');
				return;
			}
			$conditions[] = "factory_id = {$this->visitor->get('factory_id')} and dis_status !=".ORDER_DIS_STATUS_APPROVE_FINANCE;
		}elseif ($user['role']==USER_MERCHANDISER_ADMIN){
			$merch_id = empty($_GET['merch_id']) ? 0 : intval($_GET['merch_id']);
			if ($merch_id) {
				$conditions[] = "merchandiser_id = $merch_id";
			}
			$mod_company_manager=&m("company_manager");
			$brand_mod =& m('brand');
			$conditions[]="o.brand_id in(select brand_id from {$brand_mod->table} where company_id in(select company_id from {$mod_company_manager->table} where uid={$this->visitor->get('user_id')}))";
		}
		else {
			$merch_id = $user['user_id'];
			$conditions[] = "merchandiser_id = $merch_id";
		}
		$conditions = ($condition ? ' AND ' : '') . implode(' AND ', $conditions);

		if($user['role']==3 || $user['role']==7 || $user['role']==USER_FACTORY || $user['role']==USER_MERCHANDISER_ADMIN)
		{
		   $condition = $condition . $conditions;
		}
        $page = $this->_get_page();
		$order = empty($_GET['order']) ? 'dis_money DESC,dis_reason_type' : str_replace('-', ' ', trim($_GET['order']));
		if ($order != 'order_create_date DESC' || $order != 'order_create_date ASC') {
			$order .= ', dis_money DESC,dis_reason_type';
		}
        $orders=$this->_order_mod->find(
                array(
                //'limit'=>"$start,$perpage",
                'conditions'=>$condition,
                    'count' => true,
                    'limit' => $page['limit'],
					'order' => $order
                )
        );

        $page['item_count'] = $this->_order_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);

        $this->_assign_common_info();
        if($_GET['search'] || $_GET['status'] =='1') {
            $this->assign('search', '1');
            $this->assign('get_para', ecm_json_encode($_GET));
        }
        $buyer_mod=&m('member');
		if ($this->_role==USER_CLIENT){
        	$buyers=$buyer_mod->find(array('conditions'=>'user_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }elseif ($this->_role==USER_MERCHANDISER){
        	$buyers=$buyer_mod->find(array('conditions'=>'freight_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }else{
        	$buyers=$buyer_mod->find(array('conditions'=>'activation=1 and role='.USER_CLIENT));
        }
        $this->assign('buyer_list',$buyers);
        $this->assign('orders',$orders);
		if ($this->visitor->get('role') == USER_MANAGER) {
			$this->assign('manager', USER_MANAGER);
		}
		$this->_curlocal("大货折扣");
		$this->display('order.cargo_discount.html');
	}
	
	//商店退货
	function store_return_goods()
	{
		$page=$_GET['page']?intval($_GET['page']):'1';
        $perpage=PERPAGE;
        $start=($page-1)*$perpage;
        $start<0 && $start=0;
		$this->_curlocal("商店退货");
        $condition=$this->_get_conditions();
		
		//显示已确认前的所有订单
		$status_str="1=1";

		$condition.=!empty($condition)?" AND {$status_str}":$status_str;
		
		$user = $this->visitor->get();
		$this->assign("user",$user);
		if ($user['role'] == USER_MANAGER) {
			$this->assign('user_manage', USER_MANAGER);
			$merch_id = empty($_GET['merch_id']) ? 0 : intval($_GET['merch_id']);
			if ($merch_id) {
				$conditions[] = "merchandiser_id = $merch_id";
			}
		} elseif ($user['role'] == USER_ASSISTANT) {
			$merch_id = empty($_GET['merch_id']) ? 0 : intval($_GET['merch_id']);
			$this->assign('user_assistant', USER_ASSISTANT);
			$merch_ids = $user['merchandiser'];
			if ($merch_id) {
				$conditions[] = "merchandiser_id = $merch_id";
			} else {
				$conditions[] = "merchandiser_id in ($merch_ids)";
			}
		} 
		elseif ($user['role'] == USER_FACTORY) {
			if (!$user['factory_id']){
				$this->show_warning('没有该工厂,如有疑问,请联系管理员');
				return;
			}
			$conditions[] = "factory_id = {$this->visitor->get('factory_id')}";
		}
		else {
			$merch_id = $user['user_id'];
			$conditions[] = "merchandiser_id = $merch_id";
		}
		$conditions = ($condition ? ' AND ' : '') . implode(' AND ', $conditions);

		if($user['role']==3 || $user['role']==7 || $user['role']==USER_FACTORY)
		{
		   $condition = $condition . $conditions;
		}
        $page = $this->_get_page();
		
		$order = empty($_GET['order']) ? 're_count,re_money' : str_replace('-', ' ', trim($_GET['order']));
		$salesre_mod=&m("order_salesreturn");
        $orders=$salesre_mod->find(
                array(
	                'conditions'=>$condition,
					'join'=>"belongs_order",
                    'count' => true,
                    'limit' => $page['limit'],
					'order' => $order
                )
        );
		//print_r($salesre_mod->db->query_log);
        $page['item_count'] = $this->_order_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);

        $this->_assign_common_info();
        if($_GET['search'] || $_GET['status'] =='1') {
            $this->assign('search', '1');
            $this->assign('get_para', ecm_json_encode($_GET));
        }
        $buyer_mod=&m('member');
		if ($this->_role==USER_CLIENT){
        	$buyers=$buyer_mod->find(array('conditions'=>'user_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }elseif ($this->_role==USER_MERCHANDISER){
        	$buyers=$buyer_mod->find(array('conditions'=>'freight_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }else{
        	$buyers=$buyer_mod->find(array('conditions'=>'activation=1 and role='.USER_CLIENT));
        }
        $this->assign('buyer_list',$buyers);
        $this->assign('orders',$orders);
		if ($this->visitor->get('role') == USER_MANAGER) {
			$this->assign('manager', USER_MANAGER);
		}
		
		$this->display('order.salesre.html');
	}
	
	//对账汇总
	function reconlist()
	{
        $page=$_GET['page']?intval($_GET['page']):'1';
		if(!isset($_SESSION['user_info']['financepwd']) || $_SESSION['user_info']['financepwd']!=Conf::get('financepwd'))
		{
			if(!IS_POST)
			{
			  $this->display('financepwdcheck.html');
			  return;
			}
			else
			{
			  $financepwd    =md5(trim($_POST['financepwd']));
			  if($financepwd==Conf::get('financepwd'))
			  {
				  $_SESSION['user_info']['financepwd']=$financepwd;
			  }
			  else
			  {
				  $this->show_warning("财务密码验证错误,请重新输入!");
				  return;
			  }
			
			}
		}

        $perpage=PERPAGE;
        $start=($page-1)*$perpage;
        $start<0 && $start=0;

        $condition=$this->_get_conditions();
		
		$user = $this->visitor->get();
		$this->assign("user",$user);
		if ($user['role'] == USER_MANAGER) {
			$this->assign('user_manage', USER_MANAGER);
			$merch_id = empty($_GET['merch_id']) ? 0 : intval($_GET['merch_id']);
			if ($merch_id) {
				$conditions[] = "merchandiser_id = $merch_id";
			}
		} elseif ($user['role'] == USER_ASSISTANT) {
			$merch_id = empty($_GET['merch_id']) ? 0 : intval($_GET['merch_id']);
			$this->assign('user_assistant', USER_ASSISTANT);
			$merch_ids = $user['merchandiser'];
			if ($merch_id) {
				$conditions[] = "merchandiser_id = $merch_id";
			} else {
				$conditions[] = "merchandiser_id in ($merch_ids)";
			}
		}
		elseif ($user['role'] == USER_FACTORY) {
			if (!$user['factory_id']){
				$this->show_warning('没有该工厂,如有疑问,请联系管理员');
				return;
			}
			$conditions[] = "factory_id = {$this->visitor->get('factory_id')}";
		}
		 else {
			$merch_id = $user['user_id'];
			$conditions[] = "merchandiser_id = $merch_id";
		}
		
		$conditions = ($condition ? ' AND ' : '') . implode(' AND ', $conditions);
		if($user['role']==3 || $user['role']==7|| $user['role']==USER_FACTORY)
		{
		   $condition = $condition . $conditions;
		}
		
		if(!empty($_GET['sample_sn'])){
			$condition .= " AND sample_sn like '%".$_GET['sample_sn']."%'";
		}
		
		$order = empty($_GET['order']) ? 'add_time DESC' : str_replace('-', ' ', trim($_GET['order']));
		if ($order != 'order_create_date DESC' || $order != 'order_create_date ASC') {
			$order .= ', add_time DESC';
		}
        $orders=$this->_order_mod->find(
                array(
                'limit'=>"$start,$perpage",
                'conditions'=>$condition,
				'count' => true,
				'order' => $order,
                )
        );
        if (!empty($orders)){
        	foreach($orders as $key=>$item)
        	{
        		$orders[$key]["is_edit"]=$this->_check_order_is_edit($item);
        		$quantity=$item['ship_count'];
        		$orders[$key]['custome_price_amount']=$quantity*$item['customer_price'];
        	}
        }

        $page = $this->_get_page($perpage);
        $page['item_count'] =$this->_order_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);
        $this->_assign_factory();
        $this->_assign_brand();
        if($_GET['search'] || $_GET['status'] =='1') {
            $this->assign('search', '1');
            $this->assign('get_para', ecm_json_encode($_GET));
        }
        $buyer_mod=&m('member');
		if ($this->_role==USER_CLIENT){
        	$buyers=$buyer_mod->find(array('conditions'=>'user_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }elseif ($this->_role==USER_MERCHANDISER){
        	$buyers=$buyer_mod->find(array('conditions'=>'freight_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }else{
        	$buyers=$buyer_mod->find(array('conditions'=>'activation=1 and role='.USER_CLIENT));
        }
        $fabric_mod =& m('fabric');
        $this->assign('fabric_list', $fabric_mod->find(array('conditions'=>'if_show = 1', 'order'=>'fabric_name ASC')));
        $feature_mod =& m('feature');
        $this->assign('feature_list', $feature_mod->find(array('conditions'=>'if_show = 1', 'order'=>'feature_name ASC')));
        $this->assign('buyer_list',$buyers);
        $sample_mod = &m('sample');
        $sample_sn_list = $sample_mod->find(array('fields'=>'sample_sn,sample_id','order'=>'sample_id ASC'));
        $this->assign('sample_sn',$sample_sn_list);
        $this->assign('fabrics',$this->_order_mod->get_common_data('fabric_shop'));
        $this->assign('styles',$this->_order_mod->get_common_data('style'));
        $this->assign('specials',$this->_order_mod->get_common_data('special'));
        $this->assign('orders',$orders);
		$this->_curlocal("对账汇总");
		$this->display('order.reconlist.html');
	}
	
	
	function reconlist_print(){
		$user=$this->visitor->get();
		if ($user['role']!=USER_FINANCE){
			$this->show_warning("no_powers_to_visit");
			return;
		}
		$release_date_start=isset($_GET['release_date_start'])?$_GET['release_date_start']:'';
		$release_date_end=isset($_GET['release_date_end'])?$_GET['release_date_end']:'';
		$order_sn=isset($_GET['order_sn'])?$_GET['order_sn']:'';
		$style_sn=isset($_GET['style_sn'])?$_GET['style_sn']:'';
		$brand_id=isset($_GET['brand_id'])?$_GET['brand_id']:'';
		$factory_id=isset($_GET['factory_id'])?$_GET['factory_id']:'';
		$status=isset($_GET['status'])?$_GET['status']:'';
		$conditions="1=1";
		if ($release_date_start){
			$conditions.=" and release_date>=".$release_date_start;
			$this->assign('release_date_start',$release_date_start);
		}
		if ($release_date_end){
			$conditions.=" and release_date<=".$release_date_end;
			$this->assign('release_date_end',$release_date_end);
		}
		if ($order_sn){
			$conditions.=" and order_sn like %".$order_sn."%";
		}
		if ($brand_id){
			$conditions.=" and brand_id =".$brand_id;
		}
		if ($factory_id){
			$conditions.=" and factory_id =".$factory_id;
		}
		if ($status=='-1'){
			
		}elseif ($status){
			$conditions.=" and status =".$status;
		}
		$orders=$this->_order_mod->find(
			array(
				'conditions'=>$conditions,
				'order' => 'factory_name desc',
			)
		);
		
		$total_amount=$this->_order_mod->get(array(
				'conditions'=>$conditions,
				'fields'=>'sum(all_work_amount) as all_amount,sum(ship_amount) as fact_amount'
			)
		);
		
		if (!empty($orders)){
			foreach($orders as $key=>$item)
			{
				$quantity=$item['ship_count'];
				$orders[$key]['custome_price_amount']=$quantity*$item['customer_price'];
			}
		}
		$this->assign('order_list',$orders);
		$this->assign('total',$total_amount);
		$this->display('order.recon_print.html');
	}
	
	//新建订单时发送邮件
	function _send_mail_on_create($order)
	{
		if(empty($order))
		{
			return false;
		}
		$user_mod =& m('member');
		$factory_id=!empty($order['factory_id'])?$order['factory_id']:"0";
		$factory_info=$user_mod->get(array(
			'conditions'=>"factory_info.factory_id={$factory_id} and activation=1",
			'join'=>'has_factory'		
		));
		$mail = get_mail('order_on_create', array('order' => $order));
 		 if(!empty($factory_info)&&!empty($factory_info['email']))
		 {
        	  $this->_mailto($factory_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
			   return true;
		 }
		  else
		  {
			  return false;
		  }

	}
	
	//订单送审批时发送邮件
	function _send_mail_on_send_approve($order)
	{
		if(empty($order))
		{
			return false;
		}
		$user_mod =& m('member');
		
		$manger_list=$user_mod->find(array(
			"conditions"=>"role ".db_create_in(array(USER_MANAGER,USER_MERCHANDISER_ADMIN))
			));
        $mail = get_mail('order_on_send_approve', array('order' => $order));
	    foreach($manger_list as $item)
		{
			if(!empty($item['email']))
			{
			$this->_mailto($item['email'], addslashes($mail['subject']), addslashes($mail['message']));
			}
		 }
		
		$finance_list=$user_mod->find(array(
			"conditions"=>"role=".USER_FINANCE
			));
			
	    foreach($finance_list as $item)
		{
			if(!empty($item['email']))
			{
			$this->_mailto($item['email'], addslashes($mail['subject']), addslashes($mail['message']));
			}
		 }
		  return true;

	}
	
   //订单财务审批通过送主管审批时发送邮件
	function _send_mail_on_to_manger_approve($order)
	{
		if(empty($order))
		{
			return false;
		}
		$user_mod =& m('member');
		
		$manger_list=$user_mod->find(array(
			"conditions"=>"role ".db_create_in(array(USER_MANAGER,USER_MERCHANDISER_ADMIN))
			));
        $mail = get_mail('order_on_to_manger_approve', array('order' => $order));
	    foreach($manger_list as $item)
		{
			if(!empty($item['email']))
			{
			$this->_mailto($item['email'], addslashes($mail['subject']), addslashes($mail['message']));
			}
		 }
		
		  return true;

	}
	
	//订单主管审批通过送财务审批时发送邮件
	function _send_mail_on_to_finance_approve($order)
	{
		if(empty($order))
		{
			return false;
		}
		$user_mod =& m('member');
		
        $mail = get_mail('order_on_to_finance_approve', array('order' => $order));
		
		$finance_list=$user_mod->find(array(
			"conditions"=>"role=".USER_FINANCE
			));
			
	    foreach($finance_list as $item)
		{
			if(!empty($item['email']))
			{
			$this->_mailto($item['email'], addslashes($mail['subject']), addslashes($mail['message']));
			}
		 }
		  return true;

	}
	
	//审批不通过时发送邮件
	function _send_mail_on_approve_not_pass($order)
	{
		if(empty($order))
		{
			return false;
		}
		$user_mod =& m('member');
		$factory_id=!empty($order['factory_id'])?$order['factory_id']:"0";
		$factory_info=$user_mod->get("factory_id={$factory_id}");
		$merchandiser_id=!empty($order['merchandiser_id'])?$order['merchandiser_id']:"0";
		$merchandiser_info=$user_mod->get("user_id={$merchandiser_id}");
		
		$mail = get_mail('order_on_approve_not_pass', array('order' => $order));
 		 if(!empty($factory_info)&&!empty($factory_info['email']))
		 {
        //	  $this->_mailto($factory_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
			  
		 }
		 if(!empty($merchandiser_info)&&!empty($merchandiser_info['email']))
		 {
        	  $this->_mailto($merchandiser_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
			   return true;
		 }
		 return true;

	}
	//审批通过待工厂确认时发送邮件
	function _send_mail_on_wait_factory_confirm($order)
	{
		if(empty($order))
		{
			return false;
		}
		$user_mod =& m('member');
		$factory_id=!empty($order['factory_id'])?$order['factory_id']:"0";
		$factory_info=$user_mod->get("factory_id={$factory_id}");
		$merchandiser_id=!empty($order['merchandiser_id'])?$order['merchandiser_id']:"0";
		$merchandiser_info=$user_mod->get("user_id={$merchandiser_id}");
		
		$mail = get_mail('order_on_wait_factory_confirm', array('order' => $order));
 		 if(!empty($factory_info)&&!empty($factory_info['email']))
		 {
        	  $this->_mailto($factory_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
			  
		 }
		 if(!empty($merchandiser_info)&&!empty($merchandiser_info['email']))
		 {
        	  $this->_mailto($merchandiser_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
			   return true;
		 }
		 return true;

	}
		
	//工厂确认订单时发送邮件
	function _send_mail_on_factory_confirm($order)
	{
		if(empty($order))
		{
			return false;
		}
		$user_mod =& m('member');
		$merchandiser_id=!empty($order['merchandiser_id'])?$order['merchandiser_id']:"0";
		$merchandiser_info=$user_mod->get("user_id={$merchandiser_id}");
		
		$mail = get_mail('order_on_factory_confirm', array('order' => $order));
 		 if(!empty($merchandiser_info)&&!empty($merchandiser_info['email']))
		 {
        	  $this->_mailto($merchandiser_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
			   return true;
		 }
		
		$manger_list=$user_mod->find(array(
			"conditions"=>"role ".db_create_in(array(USER_MANAGER,USER_MERCHANDISER_ADMIN))
			));
	    foreach($manger_list as $item)
		{
			if(!empty($item['email']))
			{
			$this->_mailto($item['email'], addslashes($mail['subject']), addslashes($mail['message']));
			}
		 }
		 
		 return true;

	}
	
	//折扣送工厂确认时发送邮件
	function _send_mail_on_disreason_send_factory($order)
	{
		if(empty($order))
		{
			return false;
		}
		$user_mod =& m('member');
		$factory_id=!empty($order['factory_id'])?$order['factory_id']:"0";
		$factory_info=$user_mod->get("factory_id={$factory_id}");
		
		$mail = get_mail('disreason_on_send_factory', array('order' => $order));
 		 if(!empty($factory_info)&&!empty($factory_info['email']))
		 {
        	  $this->_mailto($factory_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
			  
		 }

		 return true;

	}
	
	//折扣工厂确认时发送邮件
	function _send_mail_on_disreason_factory_confirm($order)
	{
		if(empty($order))
		{
			return false;
		}
		$user_mod =& m('member');
		$merchandiser_id=!empty($order['merchandiser_id'])?$order['merchandiser_id']:"0";
		$merchandiser_info=$user_mod->get("user_id={$merchandiser_id}");
		
		$mail = get_mail('disreason_on_factory_confirm', array('order' => $order));
		 if(!empty($merchandiser_info)&&!empty($merchandiser_info['email']))
		 {
        	  $this->_mailto($merchandiser_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
			   return true;
		 }
		 return true;

	}
	
	//商店退货新建时发送邮件
	function _send_mail_on_salesre_new($order,$salesre)
	{
		if(empty($order))
		{
			return false;
		}
		$user_mod =& m('member');
		$factory_id=!empty($order['factory_id'])?$order['factory_id']:"0";
		$factory_info=$user_mod->get("factory_id={$factory_id}");
		
		$mail = get_mail('sales_return_on_new', array('order' => $order,'salesre' => $salesre));
 		 if(!empty($factory_info)&&!empty($factory_info['email']))
		 {
        	  $this->_mailto($factory_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
			  
		 }

		$finance_list=$user_mod->find(array(
			"conditions"=>"role=".USER_FINANCE
			));
			
	    foreach($finance_list as $item)
		{
			if(!empty($item['email']))
			{
			$this->_mailto($item['email'], addslashes($mail['subject']), addslashes($mail['message']));
			}
		 }
		 
		 return true;

	}
	
	//商店退货确认时发送邮件
	function _send_mail_on_salesre_confirm($order,$salesre)
	{
		if(empty($order))
		{
			return false;
		}
		$user_mod =& m('member');
		$mail = get_mail('sales_return_on_confirm', array('order' => $order,'salesre' => $salesre));

		$finance_list=$user_mod->find(array(
			"conditions"=>"role=".USER_FINANCE
			));
			
	    foreach($finance_list as $item)
		{
			if(!empty($item['email']))
			{
			$this->_mailto($item['email'], addslashes($mail['subject']), addslashes($mail['message']));
			}
		 }
		 
	   $civilian_list=$user_mod->find(array(
			"conditions"=>"role=".USER_CIVILIAN
			));
			
	    foreach($civilian_list as $item)
		{
			if(!empty($item['email']))
			{
			$this->_mailto($item['email'], addslashes($mail['subject']), addslashes($mail['message']));
			}
		 }
		 
		 return true;

	}
	
	//装箱单提交船务时发送邮件
	function _send_mail_on_submit_chuanwu($order)
	{
		if(empty($order))
		{
			return false;
		}
		$user_mod =& m('member');
		
		$mail = get_mail('pack_on_submit_chuanwu', array('order' => $order,'salesre' => $salesre));

		$chuanwu_list=$user_mod->find(array(
			"conditions"=>"role=".USER_CHUANWU
			));
			
	    foreach($chuanwu_list as $item)
		{
			if(!empty($item['email']))
			{
			$this->_mailto($item['email'], addslashes($mail['subject']), addslashes($mail['message']));
			}
		 }
		 
		 return true;

	}
	
	//装箱单船务确认时发送邮件
	function _send_mail_on_chuanwu_confirm($order)
	{
		if(empty($order))
		{
			return false;
		}
		$user_mod =& m('member');
		$factory_id=!empty($order['factory_id'])?$order['factory_id']:"0";
		$factory_info=$user_mod->get("factory_id={$factory_id}");
		
		$mail = get_mail('pack_on_chuanwu_confirm', array('order' => $order,'salesre' => $salesre));
 		 if(!empty($factory_info)&&!empty($factory_info['email']))
		 {
        	  $this->_mailto($factory_info['email'], addslashes($mail['subject']), addslashes($mail['message']));
			  
		 }

		 return true;

	}
	//审批不通过
	function approve_not_pass()
	{
	 $this->display('order.form_approve_not_pass.html');
	}
	
	//大货折扣编辑
	function disedit()
	{
		$order_id=isset($_GET["order_id"])?intval($_GET["order_id"]):0;
		$submit_val=isset($_POST["submit"])?trim($_POST["submit"]):"";
		$order_info=$this->_order_mod->get($order_id);
		$user=$this->visitor->get();
		if(empty($order_info))
		{
			$this->show_warning('未找到此折扣对应的订单信息!');
			return;
		}
		
		if(IS_POST)
		{
			  $dis_data=array();
			  $dis_form_data=array(
				   "dis_reason_type"=>isset($_POST["dis"]["dis_reason_type"])?trim($_POST["dis"]["dis_reason_type"]):"",
				  "dis_money"=>isset($_POST["dis"]["dis_money"])?floatval($_POST["dis"]["dis_money"]):"",
				  "dis_reason"=>isset($_POST["dis"]["dis_reason"])?trim($_POST["dis"]["dis_reason"]):""
			  );
			  
			  if($order_info['dis_status']==ORDER_DIS_STATUS_NO)
			  {
				   $dis_data=$dis_form_data;
				   if($submit_val=="送工厂确认" && ($user['role']==USER_MERCHANDISER|| $user['role']==USER_MANAGER))
				   {
				  $dis_data["dis_status"]=ORDER_DIS_STATUS_SEND_FACTORY;
				   }
			  }
			  elseif($order_info['dis_status']==ORDER_DIS_STATUS_SEND_FACTORY )
			  {
				   if($submit_val=="确认" && $user['role']==USER_FACTORY)
				   {
				   $dis_data["dis_status"]=ORDER_DIS_STATUS_FACTORY_CONFIRM;
				    $dis_data["goods_discount"]=$order_info['dis_money'];
					$ship_amount=floatval($order_info['dealwith_amount'])-floatval($order_info['dis_money']);
					$dis_data["ship_amount"]=$ship_amount;
					$dis_data["dis_isreturn"]=isset($_POST["dis"]["dis_isreturn"])?intval($_POST["dis"]["dis_isreturn"]):0;
				   }
				   elseif($user['role']==USER_MANAGER || $user['role']==USER_MERCHANDISER)
				   {
					$dis_data=$dis_form_data;
				   }
			  }
			//  print_r($dis_data);exit();
			  $this->_order_mod->edit($order_id,$dis_data );
			  if ($this->_order_mod->get_error()) {
				  $this->show_warning($this->_order_mod->get_error());
				  return;
			  }
			  
			  //状态变动时发送邮件和写记录
			  $new_order_info=$this->_order_mod->get($order_id);
			  $new_order_info['dis_isreturn']=empty($new_order_info['dis_isreturn'])?"否":"是";
			  $mod_pro_records=&m("pro_records");
			  $pro_data=array(
					"type"=>PRO_RECORDS_ORDER,
					"key_id"=>$order_id,
					"rec_name"=>$this->visitor->get("user_name"),

					"rec_time"=>gmtime()			
				);
			  if($order_info['dis_status']==ORDER_DIS_STATUS_NO&&$new_order_info['dis_status']==ORDER_DIS_STATUS_SEND_FACTORY )
			  {
				  $this->_send_mail_on_disreason_send_factory($new_order_info);
				   $pro_data["rec_buff"]="提交折扣并送工厂";
				   
			  }
			  elseif($order_info['dis_status']==ORDER_DIS_STATUS_SEND_FACTORY&&$new_order_info['dis_status']==ORDER_DIS_STATUS_FACTORY_CONFIRM )
			  {
				  $this->_send_mail_on_disreason_factory_confirm($new_order_info);
				  $pro_data["rec_buff"]="工厂已确认折扣";
				  
			  }
			  if(!$mod_pro_records->add($pro_data))
			  {
				 $this->show_warning($mod_pro_records->get_error());
			  }
			  
			header("location:index.php?app=order&act=edit&id={$order_id}");
		}
	}
	
	
	function AjaxDisreasonTypeAdd()
	{

		if (IS_POST) {
			$type_name = trim($_POST['type_name']);
			if (!$type_name) {
				echo ecm_json_encode(array('done'=>false,'msg'=>Lang::get('折扣原因类型名称不能为空!')));
				return;
			}
			$disreason_type_mod=&m("disreason_type");
			
			if (!$disreason_type_mod->unique($type_name)) {
				echo ecm_json_encode(array('done'=>false,'msg'=>Lang::get('折扣原因类型名称已存在')));
				return;
			}
			$data = array(
				'type_name' => $type_name
			);
			$disreason_type_id = $disreason_type_mod->add($data);
			if (!$disreason_type_id) {
				echo ecm_json_encode(array('done'=>false,'msg'=>$this->_error($disreason_type_mod->get_error())));
				return;
			}
			echo ecm_json_encode(array('done'=>true,'msg'=>Lang::get('增加折扣原因类型成功'),'disreason_type_id'=>$disreason_type_id));
		} else {
			echo ecm_json_encode(array('done'=>false,'msg'=>'请提交折扣原因类型名称！'));
		}
	}
	
	
	//商店退货编辑
	function regoods_edit()
	{
		$order_id=isset($_GET["order_id"])?intval($_GET["order_id"]):0;
		$submit_val=isset($_POST["submit"])?trim($_POST["submit"]):"";
		$order_info=$this->_order_mod->get($order_id);
		$salesre_mod=&m("order_salesreturn");
	    $mod_pro_records=&m("pro_records");
		$user=$this->visitor->get();
		  
		if(empty($order_info))
		{
			$this->show_warning('未找到对应的订单信息!');
			return;
		}

		$re_list=$salesre_mod->find(array('conditions'=>"order_id={$order_id}",'order'=>'re_date desc'));
		if(!IS_POST)
		{
			$salesre_sum_info=$salesre_mod->get(array(
			  'conditions'=>"order_id={$order_id}",
			  'fields'=>'sum(re_count) as re_count_sum,sum(re_money) as re_money_sum'
			  ));
			$this->assign("salesre_sum_info",$salesre_sum_info);
			$this->assign("now",gmtime());
			$this->assign("re_list",$re_list);
			$this->assign("order",$order_info);
			$this->_curlocal("商店退货");
			$this->display('order.re_goods.html');
		}
		else
		{
			
			if($user['role']!=USER_CIVILIAN)
			{
				$this->show_warning('无权限新增退货信息!');
				return;
			}
			  $sales_data=array();
			  $pro_data=array(
					"type"=>PRO_RECORDS_ORDER,
					"key_id"=>$order_id,
					"rec_name"=>$this->visitor->get("user_name"),
					"rec_time"=>gmtime()			
				);
				
			 //处理商店退货界面的新建操作
			  if($submit_val=="新建")
			  {
				$sales_form_data=array(
					 "re_date"=>isset($_POST["re_date"])?gmstr2time($_POST["re_date"]):0,
					"re_count"=>isset($_POST["re_count"])?intval($_POST["re_count"]):0,
					 "re_is_back"=>isset($_POST["re_is_back"])?intval($_POST["re_is_back"]):0
				);
				$sales_form_data['re_money']=$sales_form_data['re_count']*$order_info['factory_price'];
				$sales_form_data['order_id']=$order_id;
				$salesre_id=$salesre_mod->add($sales_form_data );
				if (!$salesre_id) {
					$this->show_warning($salesre_mod->get_error());
					return;
				}
				  $sales_form_data['re_is_back']=empty($sales_form_data['re_is_back'])?"否":"是";
				 $this->_send_mail_on_salesre_new($order_info,$sales_form_data);
				 $pro_data["rec_buff"]="新增本月退货";
				 if(!$mod_pro_records->add($pro_data))
				{
				   $this->show_warning($mod_pro_records->get_error());
				}
				echo '<script type="text/javascript">location.href="'.$_SERVER['REQUEST_URI'].'";</script>';
				return;
			  }
			  
			  header("location:index.php?app=order&act=edit&id={$order_id}");
		}
	}
	
	//确认商店退货信息
	function return_goods_view()
	{
		$order_id=isset($_GET["order_id"])?intval($_GET["order_id"]):0;
		$submit_val=isset($_POST["submit"])?trim($_POST["submit"]):"";
		$order_info=$this->_order_mod->get($order_id);
		$salesre_mod=&m("order_salesreturn");
	    $mod_pro_records=&m("pro_records");
		$user=$this->visitor->get();
		  
		if(empty($order_info))
		{
			$this->show_warning('未找到对应的订单信息!');
			return;
		}

		$re_list=$salesre_mod->find(array('conditions'=>"order_id={$order_id}",'order'=>'re_date desc'));
		if(!IS_POST)
		{
			$salesre_sum_info=$salesre_mod->get(array(
			  'conditions'=>"order_id={$order_id}",
			  'fields'=>'sum(re_count) as re_count_sum,sum(re_money) as re_money_sum'
			  ));
			$this->assign("salesre_sum_info",$salesre_sum_info);
			$this->assign("now",gmtime());
			$this->assign("re_list",$re_list);
			$this->assign("order",$order_info);
			$this->_curlocal("商店退货");
			$this->display('order.re_goods.html');
		}
		else
		{
		  $rid=isset($_POST["rid"])?intval($_POST["rid"]):0;
		  $salesre_mod=&m("order_salesreturn");
		  $mod_pro_records=&m("pro_records");
		  $salesre_info=$salesre_mod->get("rid={$rid} AND re_status=".SALES_RETURN_STATUS_NEW);
  
		  $user=$this->visitor->get();
		  if(empty($salesre_info))
		  {
			  $this->show_warning('未找到对应的退货信息!');
			  return;
		  }
		  $order_info=$this->_order_mod->get($salesre_info['order_id']);
		  if($user['role']!=USER_FACTORY || $order_info['factory_id']!=$user['factory_id'])
		  {
			  $this->show_warning('无权限确认此退货信息!');
			  return;
		  }
		   $re_data=array(
		   're_is_back'=>isset($_POST["re_is_back"])?intval($_POST["re_is_back"]):0,
		   "re_status"=>SALES_RETURN_STATUS_CONFIRM
		    );
		   $salesre_mod->edit("rid={$rid}",$re_data);
		   if ($salesre_mod->get_error()) {
				$this->show_warning($salesre_mod->get_error());
				return;
			}
			
			$salesre_sum_info=$salesre_mod->get(array(
			'conditions'=>"order_id={$salesre_info['order_id']} AND re_status=".SALES_RETURN_STATUS_CONFIRM,
			'fields'=>'sum(re_count) re_count_sum,sum(re_money) re_money_sum'
			));
			
			$this->_order_mod->edit("order_id={$salesre_info['order_id']}",array('re_count_sum'=>$salesre_sum_info['re_count_sum'],'re_money_sum'=>$salesre_sum_info['re_money_sum']));
		   if ($this->_order_mod->get_error()) {
				$this->show_warning($this->_order_mod->get_error());
				return;
			}
			//写入进度信息及发送邮件
			$pro_data=array(
				"type"=>PRO_RECORDS_ORDER,
				"key_id"=>$salesre_info['order_id'],
				"rec_name"=>$this->visitor->get("user_name"),
				"rec_time"=>gmtime(),
				"rec_buff"=>"确认本月退货"	
			); 
			if(!$mod_pro_records->add($pro_data))
			{
			   $this->show_warning($mod_pro_records->get_error());
			}
			$salesre_info=$salesre_mod->get("rid={$rid}");
			$salesre_info['re_is_back']=empty($salesre_info['re_is_back'])?"否":"是";
			$this->_send_mail_on_salesre_confirm($order_info,$salesre_info);
			
			echo '<script type="text/javascript">location.href="'.$_SERVER['REQUEST_URI'].'";</script>';
				return;
			//$this->show_message("确认退货信息成功");
		}
	}
	
	//删除商店退货
	function drop_re_goods(){
		$rid=isset($_GET["rid"])?intval($_GET["rid"]):0;
		$salesre_mod=&m("order_salesreturn");
		if (!$rid){
			$this->show_warning("删除错误！不存在该商店退货");
			return;
		}
		if($this->visitor->get('role')!=USER_CIVILIAN){
			$this->show_warning("no_powers_to_visit");
			return;
		}
		$salesre_mod->drop($rid);
		if ($salesre_mod->has_error()){
			$this->show_warning($salesre_mod->get_error());
			return;
		}
		$this->show_message("删除成功");
	}


	static function _assign_sizename($obj_app,$cq_sn_id=NULL,$size_sn_id=NULL)
	{
		//赋值颜色数量尺寸名称列表
		$sizename_mod=&m("sizename");
		$sizename_list=$sizename_mod->find(array(
			'conditions'=>'',
			'order'=>'snid'
		));
		$obj_app->assign('sizename_list',$sizename_list);
		$obj_app->assign('sizename_list_json',ecm_json_encode($sizename_list));
		$default_sizename=current($sizename_list);
		$curr_cq_sizename=!empty($cq_sn_id)?$sizename_list[$cq_sn_id]:$default_sizename;
		$curr_size_sizename=!empty($size_sn_id)?$sizename_list[$size_sn_id]:$default_sizename;

		$obj_app->assign('curr_cq_sizename',$curr_cq_sizename);
		$obj_app->assign('curr_size_sizename',$curr_size_sizename);
	}

	/**获取添加的实际出货数
	 * @Author: magic<zhongguovu@gmail.com>
	 * @Date: 2016-11-4 21:00:00
	 * @return array
	 */
	function _getPack($order_id){
		$packlist_mod=&m("order_packlist");

		$pask_lists=$packlist_mod->getall("select SUM(size_v1*box_cnt) as size_v1,SUM(size_v2*box_cnt) as size_v2,SUM(size_v3*box_cnt) as size_v3,
SUM(size_v4*box_cnt) as size_v4,SUM(size_v5*box_cnt) as size_v5,SUM(size_v6*box_cnt) as size_v6,pid,color,

SUM(size_v1*box_cnt)+SUM(size_v2*box_cnt)+SUM(size_v3*box_cnt)+SUM(size_v4*box_cnt)+SUM(size_v5*box_cnt)+SUM(size_v6*box_cnt) as total,
SUM(box_cnt) as carton_num,last_box,
GROUP_CONCAT(box_num) as carton_no

from {$packlist_mod->table} WHERE order_id={$order_id} group by color order by pid desc");



		$row = array();
		$k = array();
		foreach ($pask_lists as $index => $value) {
			$row["size_v1"]+=$value['size_v1'];
			$row["size_v2"]+=$value['size_v2'];
			$row["size_v3"]+=$value['size_v3'];
			$row["size_v4"]+=$value['size_v4'];
			$row["size_v5"]+=$value['size_v5'];
			$row["size_v6"]+=$value['size_v6'];
//				$row["pid"]=
//				$row["color"]=


			$row["total"] += $value["total"];

//			if ($value['last_box'] == 0) {//不包含尾箱的箱数
				$row["carton_num"] += $value["carton_num"];
//				echo $value["carton_num"];
//				echo $value["last_box"];
//			}
		}
//		var_dump($k);
		$row["carton_no"] = '尾箱号:';

		$box_result=$packlist_mod->find(array('fields'=>'box_num,box_cnt','conditions'=>"order_id={$order_id} AND last_box=1",'order'=>'pid asc'));
//echo $row["carton_num"];

//		var_dump($box_result);

		$box_str='';$last_n = 0;
		foreach ($box_result as $index => $item) {
			$box_str .=$item['box_num'].',';
			$last_n += intval($item['box_cnt']);
		}
//		echo $last_n;
		$box_str = substr($box_str,0,-1);

		$box_arr = explode(',',$box_str);

		$box_arr = array_unique($box_arr);
		if($box_str){
			$row["carton_num"] -= $last_n;
		$row["carton_num"] +=count($box_arr);
		}
		$this->countBox=$row["carton_num"];
//var_dump($row["carton_num"]);
//		var_dump(count($box_arr));die();




		$box_str = implode(',',$box_arr);


		$row["carton_no"].=$box_str;

		$pask_lists = array_merge($pask_lists,array($row));
		return $pask_lists;

	}

	/**TODO 比较客人订单数量
	 * @Author: magic
	 * @Date: 2016-11-10
	 * @param $ss_id
	 * @param $color
	 * @param $row		//输入的值  size_v1
	 * @return mixed
	 */
	public function getDiffCqData($ss_id,$color,$row){
//		var_dump($ss_id);die();
		$cq_mod =& m('cq');
//		$cq_info = $cq_mod->find(array("conditions"=>"ss_id=".$ss_id." AND color_desc='".$color."'"));
		//v6
		$cq_info = $cq_mod->getRow("select * from $cq_mod->table WHERE ss_id=" . $ss_id . " AND color_desc='" . $color . "'");


		if (empty($cq_info)) {
			return false;
		}

		$result = array();

		$result['v1'] = $v6 = $this->_jumpCq($cq_info['v6'], $cq_info['total'],$row['size_v1']);
		$result['v2'] = $v8 = $this->_jumpCq($cq_info['v8'], $cq_info['total'],$row['size_v2']);
		$result['v3'] = $v10 = $this->_jumpCq($cq_info['v10'], $cq_info['total'],$row['size_v3']);
		$result['v4'] = $v12 = $this->_jumpCq($cq_info['v12'], $cq_info['total'],$row['size_v4']);
		$result['v5'] = $v14 = $this->_jumpCq($cq_info['v14'], $cq_info['total'],$row['size_v5']);
		$result['v6'] = $v16 = $this->_jumpCq($cq_info['v16'], $cq_info['total'],$row['size_v6']);




//var_dump($cq_info['total']);
//var_dump($row['total']);
//		echo 1;
//var_dump($result);

//		die();
//		$result['v1'] = $v6 = $this->_jumpCq($cq_info['total'], $row['size_v1']);
//		$result['v2'] = $v8 = $this->_jumpCq($cq_info['total'], $row['size_v2']);
//		$result['v3'] = $v10 = $this->_jumpCq($cq_info['total'], $row['size_v3']);
//		$result['v4'] = $v12 = $this->_jumpCq($cq_info['total'], $row['size_v4']);
//		$result['v5'] = $v14 = $this->_jumpCq($cq_info['total'], $row['size_v5']);
//		$result['v6'] = $v16 = $this->_jumpCq($cq_info['total'], $row['size_v6']);

		$k = 0;
		foreach ($result as $index => $item) {
			$k = $item>0?1:0;
			if($k>0)
				break;
		}

		$result['v0'] = $color;


		$totals= intval($row['total']);//输入的总数
//		var_dump($totals);die();

		$cq_info_total= intval($cq_info['total']);

		$s = 0;
		if($k>0){
			$s=$cq_info_total > 400?1:0;
		}


//		echo $s;
//		echo $k;
//		echo $cq_info_total;
//		die();

		if ($cq_info_total > 400) {
			$dy = $cq_info_total + 50; //大于>$i
			$xy = $cq_info_total - 50; //小于<$i

//		$result = 0;
			if ($totals > $dy || $totals < $xy) {
				$k = 1;
				$s=$s>0?$s:2;
			}
		}


		$result = $k>0?$result:false;

		$r = array(
			'result'=>$result,
			'd'=>$s
		);
		return $r;
	}

	/**比较2个数相差百分比  0--400  +-10%  >400 +-5%
	 * @Author: magic
	 * @Date: 2016-11-6
	 * @param $sq_size
	 * @param $total
	 * @param $pack_size
	 * @return int  如果为1 则不符合+-5;
	 */
	private function _jumpCq($sq_size,$total,$pack_size){


		$sq_size = intval($sq_size);
		$pack_size = intval($pack_size);
		$total = intval($total);

//		var_dump($sq_size);//die();

		$result = 0;
		if ($sq_size != 0) {


			$i = $total > 400 ? 0.05 : 0.10;//百分比

			$dy = $sq_size + $sq_size * $i; //大于>$i

			$xy = $sq_size - $sq_size * $i; //小于<$i


			if ($pack_size > $dy || $pack_size < $xy) {
				$result = 1;
			}
		}

		return $result;
	}


	/** todo 装箱单
	 * @Author: magic
	 * @Date: 2016-10-24
	 */
	function packedit()
	{
		$order_id=isset($_GET["order_id"])?intval($_GET["order_id"]):0;
		$submit_val=isset($_POST["submit"])?trim($_POST["submit"]):"";
		$order_info=$this->_order_mod->get($order_id);
		if($order_info['brand_id'])
		{
		$mod_brand=&m("brand");
		$brand_info=$mod_brand->get(array(
		'conditions'=>"brand_id={$order_info['brand_id']}",
		'join'		=>"belong_company"
		));
		$order_info["company_name"]=$brand_info["company_name"];
		}
		$packlist_mod=&m("order_packlist");
	    $mod_pro_records=&m("pro_records");
		$ss_mod=&m("single_system");
		$cq_mod=&m("cq");
		
		$user=$this->visitor->get();
		  
		if(empty($order_info))
		{
			$this->show_warning('未找到对应的订单信息!');
			return;
		}
		$ss_info=$ss_mod->get("order_id={$order_id}");
		//赋值颜色数量类型
		$ss_cq_type=LANG::get("ss_cq_type");
		$cq_type=!empty($ss_info)?$ss_info['cq_type']:0;
		$this->assign("curr_cq_type",$ss_cq_type[$cq_type]);
		//赋值尺寸表类型
		require(ROOT_PATH.'/app/ss.app.php');
		SsApp::_assign_sizename($this,$ss_info['cq_sn_id'],NULL);
		
		$ss_id=isset($ss_info['ss_id'])?$ss_info['ss_id']:0;
		$color_list=$cq_mod->find(array('conditions'=>"ss_id={$ss_id}",'order'=>'cq_id desc',"fields"=>"color_desc color"));
		$this->assign("color_list",$color_list);

		$pask_list=$packlist_mod->find(array('conditions'=>"order_id={$order_id}",'order'=>'pid asc'));

		if(!IS_POST)
		{
			$pask_sum_info=$packlist_mod->get(array(
			  'conditions'=>"order_id={$order_id}",
			  'fields'=>'sum(box_cnt) as box_cnt_sum,sum(total_cnt) as total_cnt_sum,sum(gross_weight) as gross_weight_sum'
			  ));
			$this->assign("pask_sum_info",$pask_sum_info);
			$this->assign("now",gmtime());
			$this->assign("pask_list",$pask_list);
			$this->assign("user",$user);
			$this->assign("order",$order_info);
			$this->_curlocal("装箱单");
//var_dump($ss_info);
			//赋值颜色数量类型
			$this->_assign_sizename($this,$ss_info['cq_sn_id'],$ss_info['size_sn_id']);

//			客人订单数量
			$cq_mod =& m('cq');
			$cq_info = $cq_mod->find(array("conditions"=>"ss_id=".$ss_id));
			$this->assign('cq_info',$cq_info);



//			$pask_lists=$packlist_mod->findall(
//				array('conditions'=>"order_id={$order_id}",
//					'fields'=>'*',
////					'fields'=>'SUM(size_v1),color',
//					'order'=>'color'
//				)
//			);

//			$pask_lists=$packlist_mod->getall("select SUM(size_v1) as size_v1,SUM(size_v2) as size_v2,SUM(size_v3) as size_v3,
//SUM(size_v4) as size_v4,SUM(size_v5) as size_v5,SUM(size_v6) as size_v6,pid,color,
//
//SUM(size_v1)+SUM(size_v2)+SUM(size_v3)+SUM(size_v4)+SUM(size_v5)+SUM(size_v6) as total,
//box_cnt as carton_num,
//GROUP_CONCAT(box_num) as carton_no
//
//from {$packlist_mod->table} WHERE order_id={$order_id} group by color order by pid desc");
//
//
//
//			$row = array();
//			foreach ($pask_lists as $index => $value) {
//				$row["size_v1"]+=$value['size_v1'];
//				$row["size_v2"]+=$value['size_v2'];
//				$row["size_v3"]+=$value['size_v3'];
//				$row["size_v4"]+=$value['size_v4'];
//				$row["size_v5"]+=$value['size_v5'];
//				$row["size_v6"]+=$value['size_v6'];
////				$row["pid"]=
////				$row["color"]=
//				$row["total"]+=$value["total"];
//				$row["carton_num"]+=$value["carton_num"];//echo $value["box_cnt"];
//
//			}
//			$row["carton_no"]='尾箱号:';
//
//			$box_result=$packlist_mod->find(array('fields'=>'box_num','conditions'=>"order_id={$order_id} AND last_box=1",'order'=>'pid asc'));
//
//			$box_str='';
//			foreach ($box_result as $index => $item) {
//				$box_str .=$item['box_num'].',';
//			}
//			$box_str = substr($box_str,0,-1);
//
//
//			$row["carton_no"].=$box_str;
//
//			$pask_lists = array_merge($pask_lists,array($row));
//			var_dump($pask_lists);//die();

			$pask_lists = $this->_getPack($order_id);

				$this->assign('pask_lists',$pask_lists);


//			实际出货数量
//			$cq_mod_reality =& m('cq_reality');
//			$cq_info1 = $cq_mod_reality->find(array("conditions"=>"ss_id=".$ss_id));
//			if(empty($cq_info1)){
//				foreach($cq_info as $v){
//					unset($v['v6']);
//					unset($v['v8']);
//					unset($v['v10']);
//					unset($v['v12']);
//					unset($v['v14']);
//					unset($v['v16']);
//					unset($v['total']);
//					$cq_mod_reality->add($v);
//				}
//			}

//			$cq_info1 = $cq_mod_reality->find(array("conditions"=>"ss_id=".$ss_id));
//			$v6 = $v8 = $v10 = $v12 = $v14 = $v16 = $total=$carton_num = 0;
//			$carton_no = '';
//			//统计总计数据
//			foreach ($cq_info1 as $index => $item) {
//				$v6 +=intval($item['v6']);
//				$v8 +=intval($item['v8']);
//				$v10 +=intval($item['v10']);
//				$v12 +=intval($item['v12']);
//				$v14 +=intval($item['v14']);
//				$v16 +=intval($item['v16']);
//				$total +=intval($item['total']);
//				$carton_num +=intval($item['carton_num']);
//				$carton_no .=$item['carton_no'];
//				$carton_no .=!empty($item['carton_no'])?',':'';
//			}
//
//			$carton_no = substr($carton_no,0,-1);


			$arr[] = array(
				'cq_id'=>1,
				'v6'=>$v6,
				'v8'=>$v8,
				'v10'=>$v10,
				'v12'=>$v12,
				'v14'=>$v14,
				'v16'=>$v16,
				'total'=>$total,
				'carton_num'=>$carton_num,
				'carton_no'=>$carton_no,
			);
			$cq_info1 = array_merge($cq_info1,$arr);
//				var_dump($cq_info1);

			$this->assign('cq_info_reality',$cq_info1);
			$this->assign('ss_id',$ss_id);



			header("Content-type: text/html; charset=utf-8");
			//test
			$pask_lists = $this->_getPack($order_id);
			$this->assign('countBox',$this->countBox);

//			var_dump($pask_lists);
			foreach ($pask_lists as $index => $value) {
				$diff_date = $this->getDiffCqData($ss_id,$value['color'],$value);
//				echo "<pre>";
//				var_dump($diff_date);
//				echo "</pre>";

			}


			$this->display('order.packform.html');
		}
		else
		{//保存数据
			
		  //写入进度信息及发送邮件
		  $pro_data=array(
			  "type"=>PRO_RECORDS_ORDER,
			  "key_id"=>$order_id,
			  "rec_name"=>$this->visitor->get("user_name"),
			  "rec_time"=>gmtime()
		  ); 

		  if($order_info['pack_status']==ORDER_PACK_STATUS_NO)
		  {



			  
			if($user['role']!=USER_FACTORY || $order_info['factory_id']!=$user['factory_id'])
			{
				$this->show_warning('无权限编辑此退货信息!');
				return;
			}
			//获取已存在的装箱单ID列表
			$pack_list_ids=array();
			foreach($pask_list as $item)
			{
				$pack_list_ids[]=$item['pid'];
			}

			$pack_add_data=array();
			$pack_edit_data=array();
			foreach($_POST["box_num"] as $key=>$item)
			{
			  $pid=isset($_POST["pid"][$key])?intval($_POST["pid"][$key]):0;

			  $temp_form_data=array(
			    "order_id"=>$order_id,
				"box_num"=>isset($_POST["box_num"][$key])?trim($_POST["box_num"][$key]):'',
				"color"=>isset($_POST["color"][$key])?trim($_POST["color"][$key]):'',
				"last_box"=>isset($_POST["last_box"][$key])?intval($_POST["last_box"][$key]):0,
				"size_v1"=>isset($_POST["size_v1"][$key])?floatval($_POST["size_v1"][$key]):0,
				"size_v2"=>isset($_POST["size_v2"][$key])?floatval($_POST["size_v2"][$key]):0,
				"size_v3"=>isset($_POST["size_v3"][$key])?floatval($_POST["size_v3"][$key]):0,
				"size_v4"=>isset($_POST["size_v4"][$key])?floatval($_POST["size_v4"][$key]):0,
				"size_v5"=>isset($_POST["size_v5"][$key])?floatval($_POST["size_v5"][$key]):0,
				"size_v6"=>isset($_POST["size_v6"][$key])?floatval($_POST["size_v6"][$key]):0,
				"amount_per_box"=>isset($_POST["amount_per_box"][$key])?intval($_POST["amount_per_box"][$key]):0,
				"box_cnt"=>isset($_POST["box_cnt"][$key])?intval($_POST["box_cnt"][$key]):0,
				"total_cnt"=>isset($_POST["total_cnt"][$key])?intval($_POST["total_cnt"][$key]):0,
				"gross_weight"=>isset($_POST["gross_weight"][$key])?floatval($_POST["gross_weight"][$key]):0,
				);
				if(!empty($temp_form_data['color']))
				{
				  if(!empty($pid) && in_array($pid,$pack_list_ids))
				  {
					  $pack_edit_data[$pid]= $temp_form_data;
//					  var_dump($_POST);
//					  var_dump($temp_form_data);
//					  die();
				  }
				  else
				  {
					  $pack_add_data[]= $temp_form_data;
				  }
				}

			}

		    $packlist_mod->add($pack_add_data);
			if ($packlist_mod->get_error()) {
				$this->show_warning($packlist_mod->get_error());
				return;
			}
					
			foreach($pack_edit_data as $key=>$item)
			{
			$packlist_mod->edit("pid={$key}",$item);
			}
			
			$drop_pids=array_diff($pack_list_ids,array_keys($pack_edit_data));
			$packlist_mod->drop(db_create_in($drop_pids,'pid'));
			if ($packlist_mod->get_error()) {
				$this->show_warning($packlist_mod->get_error());
				return;
			}
			if($submit_val=="提交船务") {
				if (count($_POST["box_num"]) == 0) {
					$this->show_warning('无装箱单数据,无法提交!');
					return;
				}

				$pask_lists = $this->_getPack($order_id);
				foreach ($pask_lists as $index => $value) {
					$diff_date = $this->getDiffCqData($ss_id, $value['color'], $value);

//					var_dump($diff_date);die();
					if(isset($diff_date['result']) && !empty($diff_date['result'])){

//						var_dump($diff_date);die();

						$msg = $diff_date['d']==0?$value['color'].'码数对应的件数不在可接受的10%以内，请检查并改正':($diff_date['d']==1?$value['color'].'码数对应的件数不在可接受的5%以内，请检查并改正':$value['color'].'实际出货合计数不能超出订单可接受范围50件，请检查并改正');
						$this->show_warning($msg);
						return;
						die();

					}
				}




			  $this->_order_mod->edit("order_id={$order_id}","pack_status=".ORDER_PACK_STATUS_SUBMIT_CHUANWU);
			  if ($this->_order_mod->get_error()) {
				  $this->show_warning($this->_order_mod->get_error());
				  return;
			  }
			  $pro_data["rec_buff"]="提交装箱单";
			  if(!$mod_pro_records->add($pro_data))
			  {
				 $this->show_warning($mod_pro_records->get_error());
			  }
			  $this->_send_mail_on_submit_chuanwu($order_info);
			}
		  }
		  elseif($order_info['pack_status']==ORDER_PACK_STATUS_SUBMIT_CHUANWU&& $submit_val=="船务确认")
		 {
			if($user['role']!=USER_CHUANWU)
			{
				$this->show_warning('无权限确认此退货信息!');
				return;
			}
			if (!$order_info['is_keep_sample']){
				$this->show_warning('请先提交大货留底才可确认出货!');
				return;
			}
			$pask_sum_info=$packlist_mod->get(array(
			  'conditions'=>"order_id={$order_id}",
			  'fields'=>'sum(box_cnt) box_cnt_sum,sum(total_cnt) total_cnt_sum,sum(gross_weight) gross_weight_sum'
			  ));
			$ship_count=!empty($pask_sum_info)?$pask_sum_info['total_cnt_sum']:0;
			$order_up_data=array(
			"pack_status"=>ORDER_PACK_STATUS_CHUANWU_CONFIRM,
			"status"=>ORDER_STATUS_SHIPPED,
			'ship_count'=>$ship_count,
			'dealwith_amount'=>floatval($order_info['factory_price'])*$ship_count,
			'ship_amount'=>floatval($order_info['factory_price'])*$ship_count-floatval($order_info['goods_discount']),
			'all_work_amount'=>floatval($order_info['work_amount'])*$ship_count,
			'release_date'=>strtotime($_POST['release_date']),
			'buyer_arrival_date'=>strtotime($_POST['buyer_arrival_date'])			
			);
			$this->_order_mod->edit("order_id={$order_id}",$order_up_data);

			if ($this->_order_mod->get_error()) {
				$this->show_warning($this->_order_mod->get_error());
				return;
			}
			$pro_data["rec_buff"]="确认装箱单";
			if(!$mod_pro_records->add($pro_data))
			{
			   $this->show_warning($mod_pro_records->get_error());
			}
			$this->_send_mail_on_chuanwu_confirm($order_info);
		 }
		elseif(in_array($order_info['pack_status'],array(ORDER_PACK_STATUS_SUBMIT_CHUANWU,ORDER_PACK_STATUS_CHUANWU_CONFIRM))&& $submit_val=="重置")
		 {
			if($user['role']!=USER_CHUANWU)
			{
				$this->show_warning('无权限确认此退货信息!');
				return;
			}
			
			// $packlist_mod->drop("order_id={$order_id}");
//			if ($packlist_mod->get_error()) {
//				$this->show_warning($packlist_mod->get_error());
//				return;
//			}
			$this->_order_mod->edit("order_id={$order_id}","pack_status=".ORDER_PACK_STATUS_NO);
			if ($this->_order_mod->get_error()) {
				$this->show_warning($this->_order_mod->get_error());
				return;
			}
			$pro_data["rec_buff"]="重置装箱单";
			if(!$mod_pro_records->add($pro_data))
			{
			   $this->show_warning($mod_pro_records->get_error());
			}
		 }
		 
		 echo '<script type="text/javascript">location.href="'.$_SERVER['REQUEST_URI'].'";</script>';
		 return;
	   }
	}

	/**todo 添加装箱单信息
	 * @Author: magic
	 * @Date: 2016-10-24
	 */
	function ajax_add_packinfo()
	{
		$order_id=isset($_GET["order_id"])?intval($_GET["order_id"]):0;
		$order_info=$this->_order_mod->get($order_id);
		$packlist_mod=&m("order_packlist");
		$user=$this->visitor->get();
		if(empty($order_info))
		{
			$this->json_error('未找到对应的订单信息!');
			return;
		}
			
		  if($order_info['pack_status']!=ORDER_PACK_STATUS_NO)
		  {
			  $this->json_error('当前装箱单状态无法增加信息!');
			  return;
		  }
		  
		  if($user['role']!=USER_FACTORY || $order_info['factory_id']!=$user['factory_id'])
		  {
			  $this->json_error('无权限编辑此退货信息!');
			  return;
		  }

		$colorStr = isset($_POST["color"]) ? trim($_POST["color"]) : '';
		$colorArr = empty($colorStr) ? array(0,0) : explode('|', $colorStr);
		$cq_id = $colorArr[1];

		$box_num = isset($_POST["box_num"]) ? trim($_POST["box_num"]) : '';
		$box_ctn =isset($_POST["box_cnt"])?intval($_POST["box_cnt"]):0;
		$form_data = array(
			"order_id" => $order_id,
			"box_num" => $box_num,
			"color" => $colorArr[0],
			"last_box"=>isset($_POST["last_box"])?intval($_POST["last_box"]):0,
			"size_v1"=>isset($_POST["size_v1"])?floatval($_POST["size_v1"]):0,
			"size_v2"=>isset($_POST["size_v2"])?floatval($_POST["size_v2"]):0,
			"size_v3"=>isset($_POST["size_v3"])?floatval($_POST["size_v3"]):0,
			"size_v4"=>isset($_POST["size_v4"])?floatval($_POST["size_v4"]):0,
			"size_v5"=>isset($_POST["size_v5"])?floatval($_POST["size_v5"]):0,
			"size_v6"=>isset($_POST["size_v6"])?floatval($_POST["size_v6"]):0,
			"amount_per_box"=>isset($_POST["amount_per_box"])?intval($_POST["amount_per_box"]):0,
			"box_cnt"=>$box_ctn,
			"total_cnt"=>isset($_POST["total_cnt"])?intval($_POST["total_cnt"]):0,
			"gross_weight"=>isset($_POST["gross_weight"])?floatval($_POST["gross_weight"]):0,
			);


		$pid=$packlist_mod->add($form_data);
		if ($packlist_mod->get_error()) {
			$this->json_error($packlist_mod->get_error());
			return;
		}

		if($cq_id && 1==2){//如果有传ID过来
		$cq_mod_reality =& m('cq_reality');

			$row = 'v10=v10+1';
			$data["v6"] = $form_data['size_v1'];
			$data["v8"] = $form_data['size_v2'];
			$data["v10"] = $form_data['size_v3'];
			$data["v12"] = $form_data['size_v4'];
			$data["v14"] = $form_data['size_v5'];
			$data["v16"] = $form_data['size_v6'];
			$data["carton_num"] = $box_ctn;
			$data["carton_no"] = "CONCAT(carton_no,'$box_num,')";
//			$data["total"] = $data["v6"]+$data["v8"]+$data["v10"]+$data["v12"]+$data["v14"]+$data["v16"];
			$dataStr = '';
			$dataCountStr = 'total=';//合计
			$dataCountNo = 'carton_no=carton_num+"2"';//合计
			foreach ($data as $index => $item) {
				if($index!='carton_no'){
				$dataStr .= $index . '=' . $index . '+' . $item . ',';
				}else{
					$dataStr .= $index . '=' . $item . ',';
				}
				if($index!='carton_num' && $index!='carton_no') {
					$dataCountStr .= '+' . $index;
				}
				}
			$dataStr = substr($dataStr, 0, -1);

			unset($form_data);
			$cq_mod_reality->edit($cq_id, $dataStr);
			$cq_mod_reality->edit($cq_id, $dataCountStr);

		}
//		die();
		
		$pask_sum_info=$packlist_mod->get(array(
		  'conditions'=>"order_id={$order_id}",
		  'fields'=>'sum(box_cnt) box_cnt_sum,sum(total_cnt) total_cnt_sum,sum(gross_weight) gross_weight_sum'
		  ));
		  
	    $pask_sum_info['pid']=$pid;
		$this->json_result($pask_sum_info,"增加装箱单信息成功");
		return;
	}
	
	//ajax获取品名货号
	function ajaxGetitem()
	{
		$fabric_shop_id=isset($_GET['fabric_shop_id'])?intval($_GET['fabric_shop_id']):0;
		$fabric_mod=&m("fabric_info");
		$item_list=$fabric_mod->find(array(
			'conditions'=>"fabric_shop_id={$fabric_shop_id}"
		));
		echo json_encode($item_list);
	}
	
	//ajax获取工厂加工报价列表
	function ajax_getquote()
	{
		$factory_id=isset($_GET['factory_id'])?intval($_GET['factory_id']):0;
	
		$factory_mod=& m('factory_info');
		$quote_info=$factory_mod->get(array(
				'conditions'=>"factory_id={$factory_id}"
		));
		$quote_mod=& m('quote');
		$arr_info=$quote_mod->get(array(
			'conditions'=>'factory_id='.$factory_id.' and if_option=1',
			'fields'=>'sum(order_num) as order_num'		
		));
		if (!empty($arr_info)){
			$quote_info['order_num']=$arr_info['order_num'];
			$quote_info['if_option']=0;
		}
		echo json_encode($quote_info);
	}
	
	
	//ajax调用裁床信息
	function ajax_getcq()
	{
		$cq_id=isset($_GET['cq_id'])?trim($_GET['cq_id']):'';
		$cq_mod=& m('cq');
		$cut_list=$cq_mod->get(array(
				'conditions'=>'cq_id='.$cq_id,
				'fields'=>'total,color_desc'
		));
		echo json_encode($cut_list);
	}
	
	//创建生产板采购单
	function add_purchase_status(){
		$order_id=isset($_GET['order_id'])?intval($_GET['order_id']):0;
		$result=array();
		$sourcing_mod=&m('sourcing_info');
		if (!$order_id){
			$result['msg']="网络连接错误，请稍后再试";
			$result['flag']=false;
			exit(json_encode($result));
		}
		$order=$this->_order_mod->get($order_id);
		if(empty($order)) {
			$result['msg']="订单不存在";
			$result['flag']=false;
			exit(json_encode($result));
		}
		$sour_info=$sourcing_mod->find(array(
			'conditions'=>'order_id='.$order_id
		));
		$fabric_order_mod=& m('fabric_order');
		$fabric_info_mod=& m('fabric_info');
		if (!empty($order['sample_id'])){
			$fabric_status_list = $fabric_info_mod->find(array(
					'conditions'=>'sample_id='.$order['sample_id'],
					'fields'=>"fabric_info.fabric_info_id,sample_id,fabric_info.description,fabric_info.fabric_shop_id,item,price,width,picture,fabric_shop_name,colors,fabric_num,phone_mob,address,cc_id,fabric_characteristics",
					'join'	=>"belongs_fabric_shop",
					'order'=>'fabric_info_id ASC'
			));
		}
		if (!empty($sour_info)){
			foreach ($sour_info as $key=>$rows){
				if ($rows['sourcing_status']<SOURCING_STATUS_FINANCE_EXAMINE){
					$s_id=$rows['sourcing_id'];
				}
			}
			if ($s_id){
				$result['flag']=true;
				$result['url']="index.php?app=purchase&act=order_sour&id=".$s_id;
			}else{
				$sour_data=array(
					'order_id'=>$order_id,
					'add_time' =>gmtime(),
					'sourcing_status'=>SOURCING_STATUS_CREATE
				);
				$sourcing_id=$sourcing_mod->add($sour_data);
				if (!$sourcing_id){
					$this->show_warning($sourcing_mod->get_error());
					exit;
				}else{
					if (!empty($fabric_status_list)){
						foreach($fabric_status_list as $key=>$item)
						{
							$fabric_data=array(
									"sourcing_id"=>$sourcing_id,
									"order_id"=>$order_id,
									"description"=>isset($item['description'])?trim($item['description']):"",
									"fabric_shop_id"=>isset($item['fabric_shop_id'])?intval($item['fabric_shop_id']):"",
									"cc_id"=>isset($item['cc_id'])?intval($item['cc_id']):0,
									"item"=>isset($item['item'])?trim($item['item']):"",
									"price"=>isset($item['price'])?trim($item['price']):"",
									"fabric_characteristics"=>isset($item['fabric_characteristics'])?trim($item['fabric_characteristics']):"",
									"colors"=>isset($item['colors'])?trim($item['colors']):"",
									"fabric_num"=>isset($item['fabric_num'])?trim($item['fabric_num']):"",
									"address"=>isset($item['address'])?trim($item['address']):"",
									"phone_mob"=>isset($item['phone_mob'])?trim($item['phone_mob']):"",
							);
							if(!empty($fabric_data['price']))
							{
								$fabric_order_mod->add($fabric_data);
							}
						}
					}
					if (strlen ( $sourcing_id ) <= 10) {
						$k = 10 - strlen ( $sourcing_id );
						for($i = 0; $i < $k; $i ++) {
							$len .= 0;
						}
						$sourcing_sn = 'CB' . $len . $sourcing_id;
					}
					$sourcing_mod->edit($sourcing_id,array('sourcing_sn'=>$sourcing_sn));
					if ($sourcing_mod->has_error()){
						$this->show_warning($sourcing_mod->get_error());
						exit;
					}
				}
				$result['msg']="创建采购单成功";
				$result['flag']=true;
				$result['url']="index.php?app=purchase&act=order_sour&id=".$sourcing_id;
			}
		}else{
			$sour_data=array(
					'order_id'=>$order_id,
					'add_time' =>gmtime(),
					'sourcing_status'=>SOURCING_STATUS_CREATE
			);
			$sourcing_id=$sourcing_mod->add($sour_data);
			if (!$sourcing_id){
				$this->show_warning($sourcing_mod->get_error());
				exit;
			}else{
				if (!empty($fabric_status_list)){
					foreach($fabric_status_list as $key=>$item)
					{
						$fabric_data=array(
								"sourcing_id"=>$sourcing_id,
								"order_id"=>$order_id,
								"description"=>isset($item['description'])?trim($item['description']):"",
								"fabric_shop_id"=>isset($item['fabric_shop_id'])?intval($item['fabric_shop_id']):"",
								"cc_id"=>isset($item['cc_id'])?intval($item['cc_id']):0,
								"item"=>isset($item['item'])?trim($item['item']):"",
								"price"=>isset($item['price'])?trim($item['price']):"",
								"fabric_characteristics"=>isset($item['fabric_characteristics'])?trim($item['fabric_characteristics']):"",
								"colors"=>isset($item['colors'])?trim($item['colors']):"",
								"fabric_num"=>isset($item['fabric_num'])?trim($item['fabric_num']):"",
								"address"=>isset($item['address'])?trim($item['address']):"",
								"phone_mob"=>isset($item['phone_mob'])?trim($item['phone_mob']):"",
						);
						if(!empty($fabric_data['price']))
						{
							$fabric_order_mod->add($fabric_data);
						}
					}
				}
				if (strlen ( $sourcing_id ) <= 10) {
					$k = 10 - strlen ( $sourcing_id );
					for($i = 0; $i < $k; $i ++) {
						$len .= 0;
					}
					$sourcing_sn = 'CB' . $len . $sourcing_id;
				}
				$sourcing_mod->edit($sourcing_id,array('sourcing_sn'=>$sourcing_sn));
				if ($sourcing_mod->has_error()){
					$this->show_warning($sourcing_mod->get_error());
					exit;
				}
			}
			$result['msg']="创建采购单成功";
			$result['flag']=true;
			$result['url']="index.php?app=purchase&act=order_sour&id=".$sourcing_id;
		}
		exit(json_encode($result));
	}
	
	
	//更新大货采购单信息
	function update_bulk_sourcing(){
		$order_id=isset($_GET['order_id'])?intval($_GET['order_id']):0;
		$btn=isset($_GET['btn'])?trim($_GET['btn']):'';
		$user=$this->visitor->get();
		$result=array();
		if (!$order_id){
			$result['msg']="没有搜索到该订单";
			$result['flag']=false;
			exit(json_encode($result));
		}
		if (!$btn){
			$result['msg']="非法操作";
			$result['flag']=false;
			exit(json_encode($result));
		}
		$fabric_info_mod=& m('fabric_info');
		if (IS_POST){
			$bulk_mod=&m('bulk_sourcing');
// 			$bulk_info=$bulk_mod->get(array(
// 				'conditions'=>'item_id='.$order_id	
// 			));
			$data=array();
			if ($btn=="保存"){
				
			}elseif ($btn=="送主管审批"){
				$data['bulk_status']=BULK_STATUS_SEND_MANAGER;
			}else{
				$result['msg']="非法操作";
				$result['flag']=false;
				exit(json_encode($result));
			}
			if (in_array($user['role'], array(USER_MERCHANDISER))){
				$new_bulk_ids=array();
				$fabric_info_list = $fabric_info_mod->find(array(
						'conditions'=>'order_id='.$order_id,
						'fields'=>"fabric_info.fabric_info_id,sample_id,fabric_info.description,fabric_info.fabric_shop_id,item,price,width,picture,fabric_shop_name,colors,fabric_num,phone_mob,address,cc_id,fabric_characteristics,fabric_info.bulk_id,fabric_info.bulk_status",
						'join'	=>"belongs_fabric_shop",
						'order'=>'fabric_info_id ASC'
				));
				$bulk_arr_id=array();
				if (!empty($fabric_info_list)){
					foreach ($fabric_info_list as $rows){
						$bulk_arr_id[]=$rows['fabric_info_id'];
					}
				}
				$fabric_bulk_ids=empty($_POST['bulk_id'])?0:$_POST['bulk_id'];
				$f_bulk=array_filter($fabric_bulk_ids);
				$bulk_diff=count($fabric_bulk_ids)-count($f_bulk);
				if ((empty($fabric_bulk_ids) && count($fabric_bulk_ids)>1) || $bulk_diff>1){
					if ($btn=="送主管审批"){
						$data['item_id']=$order_id;
						$data['bulk_time'] =gmtime();
						$bulk_id=$bulk_mod->add($data);
						if (!$bulk_id){
							$this->show_warning($bulk_mod->get_error());
							exit;
						}
						if (strlen ( $bulk_id ) <= 10) {
							$k = 10 - strlen ( $bulk_id );
							for($i = 0; $i < $k; $i ++) {
								$len .= 0;
							}
							$bulk_sn = 'DH' . $len . $bulk_id;
						}
						$bulk_mod->edit($bulk_id,array('bulk_sn'=>$bulk_sn));
						if ($bulk_mod->has_error()){
							$this->show_warning($bulk_mod->get_error());
							exit;
						}
					}
				}
				foreach($_POST['bulk_shop_name'] as $key=>$item)
				{
					$bulk_info_id=isset($_POST['bulk_info_id'][$key])?intval($_POST['bulk_info_id'][$key]):0;
					$bulk_status=isset($_POST['bulk_status'][$key])?intval($_POST['bulk_status'][$key]):null;
					$bulk_data=array(
						"order_id"=>$order_id,
						"description"=>isset($_POST['bulk_description'][$key])?trim($_POST['bulk_description'][$key]):"",
						"fabric_shop_id"=>isset($_POST['bulk_shop_name'][$key])?intval($_POST['bulk_shop_name'][$key]):"",
						"cc_id"=>isset($_POST['bulk_cc_id'][$key])?intval($_POST['bulk_cc_id'][$key]):0,
						"item"=>isset($_POST['bulk_item'][$key])?trim($_POST['bulk_item'][$key]):"",
						"price"=>isset($_POST['bulk_price'][$key])?trim($_POST['bulk_price'][$key]):"",
						"colors"=>isset($_POST['bulk_colors'][$key])?trim($_POST['bulk_colors'][$key]):"",
						"fabric_num"=>isset($_POST['bulk_num'][$key])?trim($_POST['bulk_num'][$key]):"",
						"address"=>isset($_POST['bulk_address'][$key])?trim($_POST['bulk_address'][$key]):"",
						"phone_mob"=>isset($_POST['bulk_phone_mob'][$key])?trim($_POST['bulk_phone_mob'][$key]):"",
					);
			
					if(!empty($bulk_data['fabric_shop_id'])&&!empty($bulk_data['item']))
					{
						if(empty($bulk_info_id) || !in_array($bulk_info_id, $bulk_arr_id))
						{
							if ($btn=="送主管审批"){
								if ($bulk_id){
									$bulk_data['bulk_status']=BULK_STATUS_SEND_MANAGER;
									$bulk_data['bulk_id']=$bulk_id;
								}
							}
							$fabric_info_mod->add($bulk_data);
						}
						else
						{
							if ($btn=="送主管审批"){
								$bulk_info=$fabric_info_mod->get($bulk_info_id);
								if(empty($bulk_info['bulk_id'])){
									if ($bulk_id){
										$bulk_data['bulk_status']=BULK_STATUS_SEND_MANAGER;
										$bulk_data['bulk_id']=$bulk_id;
									}
								}
							}
							$new_bulk_ids[]=$bulk_info_id;
			
							$fabric_info_mod->edit("fabric_info_id={$bulk_info_id}",$bulk_data);
						}
					}
				}
			
				if (!empty($fabric_info_list)){
					foreach($fabric_info_list as $item)
					{
						if(!in_array($item['fabric_info_id'],$new_bulk_ids))
						{
							$fabric_info_mod->drop("fabric_info_id={$item['fabric_info_id']}");
						}
					}
				}
				
// 				if (!empty($bulk_info)){
// 					$bulk_mod->edit($bulk_id,$data);
// 					if ($bulk_mod->has_error()){
// 						$this->show_warning($bulk_mod->get_error());
// 						exit;
// 					}
// 				}else{
			}else{
				$result['msg']="没有权限操作该大货采购单";
				$result['flag']=false;
				exit(json_encode($result));
			}
			$result['msg']="操作成功";
			$result['flag']=true;
			$result['url']="index.php?app=order&act=edit&id=".$order_id;
			exit(json_encode($result));
		}
	}
	
	//收货排期
	function receipt_list(){
		$page=$_GET['page']?intval($_GET['page']):'1';
		$perpage=PERPAGE;
		$start=($page-1)*$perpage;
		$start<0 && $start=0;
		$this->_curlocal("收货排期列表");
		$qc_factory_mod=& m('qcfactory');
		
		$condition=$this->_get_conditions();
		
		//显示已确认前的所有订单
		$user = $this->visitor->get();
		if ($user['role']==USER_QC){
			$qc_list=$this->qc_factory_info($user);
			if (!empty($condition)){
				$condition .=' and '.$qc_list;
			}else{
				$condition .=$qc_list;
			}
		}
		$this->assign("user",$user);
		$receipt_mod=&m('receipt');
		$page = $this->_get_page();
		$order = empty($_GET['order']) ? 'add_time DESC' : str_replace('-', ' ', trim($_GET['order']));
		if ($order != 'order_create_date DESC' || $order != 'order_create_date ASC') {
			$order .= ', add_time DESC';
		}
		$receipt_list=$receipt_mod->find(
				array(
					'join'=>'belongs_order',
					'conditions'=>$condition,
					'count' => true,
					'limit' => $page['limit'],
					'order' => $order
				)
		);
		$page['item_count'] = $receipt_mod->getCount();
		$this->_format_page($page);
		$this->assign('page_info', $page);
		if (!empty($receipt_list)){
			$ss_mod=&m('ss');
			foreach ($receipt_list as $key=>$rows){
				$order_id=$rows['order_id'];
				$ss_info=$ss_mod->get('order_id='.$order_id);
				$receipt_list[$key]['ss_id']=$ss_info['ss_id'];
				$qc_info=$qc_factory_mod->get(array(
					'join'=>'belongs_to_qc_name',
					'conditions'=>'order_id='.$order_id.' and role'.db_create_in(array(USER_QC,USER_OUTGOING)),
					'fields'=>'user_name'
				));
				if (!empty($qc_info)){
					$receipt_list[$key]['qc_name']=$qc_info['user_name'];
				}
			}
		}
		
		$this->_assign_common_info();
		$buyer_mod=&m('member');
		if ($this->_role==USER_CLIENT){
        	$buyers=$buyer_mod->find(array('conditions'=>'user_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }elseif ($this->_role==USER_MERCHANDISER){
        	$buyers=$buyer_mod->find(array('conditions'=>'freight_id='.$this->user['user_id'].' and activation=1 and role='.USER_CLIENT));
        }else{
        	$buyers=$buyer_mod->find(array('conditions'=>'activation=1 and role='.USER_CLIENT));
        }
		$this->assign('buyer_list',$buyers);
		$this->assign('receipt_list',$receipt_list);
		$this->display('order.receipt.html');
	}
	
	
	//添加qc查货进度
	function add_process(){
		$order_id=isset($_GET['order_id'])?intval($_GET['order_id']):0;
		$result=array();
		$process_mod=&m('qc_process');
		if (!$order_id){
			$result['msg']="没有搜索到该订单";
			$result['flag']=false;
			exit(json_encode($result));
		}
		$order_info=$this->_order_mod->get($order_id);
		if (empty($order_info)){
			$result['msg']="没有搜索到该订单";
			$result['flag']=false;
			exit(json_encode($result));
		}
		if ($_POST['process_content']){
			$process_data=array(
				"order_id"=>$order_id,
				"receipt_time"=>strtotime($_POST['receipt_time']),
				"process_content"=>trim($_POST['process_content']),
				"qc_id"=>$this->visitor->get('user_id')
			);
			$p_data=array_filter($process_data);
			if(!empty($p_data))
			{
				$process_id=$process_mod->add($p_data);
				if ($process_mod->has_error()){
					$this->show_warning($process_mod->get_error());
					exit;
				}
			}
		}
		if ($process_id){
			$process_info=$process_mod->get(array(
					'join'=>'belongs_process_order',
					'fields'=>"receipt_time,process_id,process_content",
					'conditions'=>$process_id
			));
			if (!empty($process_info['receipt_time'])){
				$process_info['process_time']=date('Y-m-d',$process_info['receipt_time']);
			}
			$process_arr_id=isset($_POST['process_arr_id'])?$_POST['process_arr_id']:"";
			$file_mod=&m('upload');
			if(!empty($process_arr_id))
			{
				$file_ids=implode(",",$process_arr_id);
				$cust_files_info=$file_mod->find(array(
						"conditions"=>"file_id in({$file_ids}) AND file_type=".BELONGS_PROCESS_RECEIPT." AND key_id=".DEFAULT_CUSTOMER_KEY_ID." and session_id='".session_id()."'"
								));
					
				foreach($cust_files_info as $item)
				{
					$file_path = str_replace(DEFAULT_CUSTOMER_KEY_ID, $process_id, $item['file_path']);
					if(!file_exists(dirname($file_path))) {
						mkdir(dirname($file_path), 0777);
					}
					rename($item['file_path'], $file_path);
					$file_mod->edit("file_id={$item['file_id']}",array(
							"file_path"=>$file_path,
							"key_id"=>$process_id,
							"session_id"=>session_id()
					));
				}
			}
			$process_info['qc_name']=$this->visitor->get('user_name');
			$result['flag']=true;
			$result['pro_data']=$process_info;
			exit(json_encode($result));
		}
	}
	
	
	//标注QC进度
	function process_tips(){
		$pid=isset($_GET['pid'])?intval($_GET['pid']):0;
		$result=array();
		if (in_array($this->visitor->get('role'), array(USER_OUTGOING,USER_MANAGER,USER_MERCHANDISER))){
			if (!$pid){
				$result['msg']="网络连接错误，请稍后再试";
				$result['flag']=false;
				exit(json_encode($result));
			}
			$process_mod=&m('qc_process');
			$process_info=$process_mod->get(array(
				'conditions'=>'process_id='.$pid	
			));
			$p_data=array();
			if ($process_info['process_status']){
				$p_data['process_status']=0;
				$result['tips']=false;
			}else{
				$p_data['process_status']=1;
				$result['tips']=true;
			}
			$process_mod->edit($pid,$p_data);
			if ($process_mod->has_error()){
				$this->show_warning($process_mod->get_error());
				exit;
			}else{
				$result['msg']="标注成功";
				$result['flag']=true;
				exit(json_encode($result));
			}
		}else{
			$this->show_warning('no_powers_to_visit');
			exit;
		}
	}
	
	//上传qc查货进度附件
	function process_upload(){
		$pid=empty($_GET['pid'])?0:intval($_GET['pid']);
		$user_info=$this->visitor->get();
		if (!$pid) {
			$this->show_warning('qc_process_not_exist');
			return;
		}
		$process_mod=&m('qc_process');
		$process_info=$process_mod->get(array(
				'join'=>'belongs_process_order',
				'conditions'=>'process_id='.$pid
		));
		if (empty($process_info)){
			$this->show_warning('qc_process_not_exist');
			return;
		}
		$file_mod=&m('upload');
		$process_info['process_file'] = $file_mod->find(array(
				'conditions' => 'file_type = ' . BELONGS_PROCESS_RECEIPT . ' AND key_id = ' . $pid,
				'order' => 'file_id ASC',
		));
		$this->assign('belongs_process_receipt',BELONGS_PROCESS_RECEIPT);
		$this->assign('process',$process_info);
		$this->assign('user',$user_info);
		$this->display('process.upload.html');
	}
	
	//删除qc查货进度
	function drop_process(){
		$pid=isset($_GET['pid'])?intval($_GET['pid']):0;
		$result=array();
		if (in_array($this->visitor->get('role'), array(USER_QC,USER_OUTGOING))){
			if (!$pid){
				$result['msg']="网络连接错误，请稍后再试";
				$result['flag']=false;
				exit(json_encode($result));
			}
			$process_mod=&m('qc_process');
			$process_mod->drop($pid);
			if ($process_mod->has_error()){
				$this->show_warning($process_mod->get_error());
				exit;
			}else{
				$result['msg']="删除成功";
				$result['flag']=true;
				exit(json_encode($result));
			}
		}else{
			$this->show_warning('no_powers_to_visit');
			exit;
		}
	}
	
	//主唛列表
	function _assign_main_label($brand_id=null){
		$main_mod=&m('main_label');
		if ($brand_id){
			$main_list=$main_mod->find(array(
					'conditions'=>'brand_id='.$brand_id
			));
		}else{
			$main_list=$main_mod->find(array(
					'order'=>'m_id desc'
			));
		}
		$this->assign('main_list',$main_list);
	}
	
	//主唛、主唛图片联动
	function ajax_mian_label_img(){
		$main_file=array();
		$m_id=isset($_GET['m_id'])?$_GET['m_id']:0;
		if ($m_id){
			$file_mod=&m('upload');
			$main_file=$file_mod->get(array(
				'conditions' => 'file_type = ' . BELONGS_MAIN_LABEL . ' AND key_id = ' . $m_id,
        		'order' => 'file_id ASC',
			));
		}
		exit(json_encode($main_file));
	}
	
	
	//挂牌列表
	function _assign_listing($brand_id=null){
		$listing_mod=&m('listing');
		if ($brand_id){
			$listing=$listing_mod->find(array(
					'conditions'=>'brand_id='.$brand_id
			));
		}else{
			$listing=$listing_mod->find(array(
					'order'=>'listing_time desc'
			));
		}
		$this->assign('listing',$listing);
	}
	
	//主唛、主唛图片联动
	function ajax_listing_img(){
		$listing_file=array();
		$l_id=isset($_GET['l_id'])?$_GET['l_id']:0;
		if ($l_id){
			$file_mod=&m('upload');
			$listing_file=$file_mod->get(array(
					'conditions' => 'file_type = ' . BELONGS_LISTING_IMG . ' AND key_id = ' . $l_id,
					'order' => 'file_id ASC',
			));
		}
		exit(json_encode($listing_file));
	}
	
	//待审批报价单
	function quote_approve(){
		$user_info=$this->visitor->get();
		$page = $this->_get_page(10);
		if (in_array($user_info['role'], array(USER_MANAGER,USER_MERCHANDISER_ADMIN))){
			$conditions=$this->_get_query_conditions(array(
					array(
							'field' => 'quote_sn',
							'equal' => 'like',
							'name'	 => 'quote_sn'
					),
					array(
							'field' => 'style_sn',
							'equal' => 'like',
							'name'	 => 'style_sn'
					)
			));
			$con=$this->_get_query_conditions(array(
					array(
							'field' => 'quote_sn',
							'equal' => 'like',
							'name'	 => 'quote_sn'
					)
			));
			if ($user_info['role']==USER_MERCHANDISER_ADMIN){
				$mod_cm=&m("company_manager");
				$mod_brand=&m("brand");
				$brand_ids=$mod_brand->find(array('conditions'=>"company_id in(select company_id from ($mod_cm->table) where uid={$this->visitor->get('user_id')})","fields"=>"brand_id"));
				$quote_approve_where=' AND brand_id'.db_create_in(array_keys($brand_ids));
			}
			$order_mod=&m('order');
			$sample_mod=&m('sample');
			$con.=" and quote_sn is not null";
			$conditions.=" and status ".db_create_in(array(ORDER_STATUS_NO_CONFIRM,ORDER_STATUS_APPROVE,ORDER_STATUS_APPROVE_FINANCE,ORDER_STATUS_APPROVE_MANAGER,ORDER_STATUS_FACTORY_CONFIRM)).' and quote_sn is not null';
			$quote_list=$order_mod->find(array(
					'conditions'=>'1=1 '.$conditions.' and quote_status = 1'.$quote_approve_where,
					'fields'=>'order_id,quote_time,quote_sn,quote_check_date,quote_status,quantity,merchandiser,style_sn,front_pic',
					'order'=>'quote_time desc',
					'count'=>true,
					'limit'=>$page['limit']
			));
			$sq_list=$sample_mod->find(array(
				'conditions'=>'1=1 '.$con.' and quote_status = 1'.$quote_approve_where,
				'fields'=>'quote_time,quote_sn,quote_check_date,quote_status,sample_id,front_pic,merchandiser_id,sample_sn',
				'order'=>'quote_time desc',
				'count'=>true,
				'limit'=>$page['limit']	
			));
			if (!empty($sq_list)){
				$member_mod=&m('member');
				foreach ($sq_list as $j=>$rows){
					$merch_id=$rows['merchandiser_id'];
					if ($merch_id){
						$member_info=$member_mod->get(array(
								'conditions'=>'user_id='.$merch_id.' and role='.USER_MERCHANDISER
						));
					}
					$sq_list[$j]['merchandiser']=$member_info['user_name'];
				}
			}
			$quote_arr=array_merge($quote_list,$sq_list);
			$page['item_count'] = $order_mod->getCount()+$sample_mod->getCount();
			$this->_format_page($page);
			$this->assign('page_info', $page);
			$this->assign('orders', $quote_arr);
		}
		$this->_curlocal(Lang::get('待审批报价'));
		$this->display('order_quote.approve.html');
	}
	
	
	//生产板进度列表
	function status(){
		$page=$_GET['page']?intval($_GET['page']):'1';
		$perpage=PERPAGE;
		$start=($page-1)*$perpage;
		$start<0 && $start=0;
		 
		$this->_curlocal("生产板进度");
		
		$condition=$this->_get_conditions();
		
		//显示正在进行的生产板的所有订单
		$status_str="product_status !=".PRODUCT_STATUS_CREATE;
		
		$condition.=!empty($condition)?" AND {$status_str}":$status_str;
		
		$user = $this->visitor->get();
		$this->assign("user",$user);
		if ($user['role'] == USER_MERCHANDISER_ADMIN) {
			$mod_company_manager=&m("company_manager");
			$brand_mod =& m('brand');
			$conditions[]="o.brand_id in(select brand_id from {$brand_mod->table} where company_id in(select company_id from {$mod_company_manager->table} where uid={$this->visitor->get('user_id')}))";
		}elseif ($user['role'] == USER_FACTORY) {
			if (!$user['factory_id']){
				$this->show_warning('没有该工厂,如有疑问,请联系管理员');
				return;
			}
			$conditions[] = "factory_id = {$this->visitor->get('factory_id')}";
		}elseif ($user['role']==USER_MANAGER){
			$conditions[]="1=1";
		}
		else {
			$merch_id = $user['user_id'];
			$conditions[] = "merchandiser_id = $merch_id";
		}
		$conditions = ($condition ? ' AND ' : '') . implode(' AND ', $conditions);
		$condition .= $conditions;
		$page = $this->_get_page();
		$order = empty($_GET['order']) ? 'product_date DESC' : str_replace('-', ' ', trim($_GET['order']));
		if ($order != 'product_date DESC' || $order != 'product_date ASC') {
			$order .= ', product_date DESC';
		}
		$orders=$this->_order_mod->find(
				array(
					'conditions'=>$condition,
					'count' => true,
					'limit' => $page['limit'],
					'order' => $order.',style_sn desc'
				)
		);
		if (!empty($orders)){
			foreach ($orders as $k=>$val){
				$orders[$k]['product_day']=round((gmtime()-$val['product_date'])/(24*3600));
			}
		}
		
		$page['item_count'] = $this->_order_mod->getCount();
		$this->_format_page($page);
		$this->assign('page_info', $page);
		
		$this->_assign_common_info();
		$this->assign('orders',$orders);
		$this->display('order.product.html');
	}
	
	
	//重置生产板
	function reset_order(){
		$role=$this->visitor->get("role");
		
		$id=$_REQUEST['id']?intval($_REQUEST['id']):0;
		if(!$id) {
			$this->msg_error( '无该订单');
			exit;
		}
		if(in_array($role, array(USER_MANAGER,USER_MERCHANDISER,USER_MERCHANDISER_ADMIN))){
			$this->_order_mod->edit($id,array('product_status'=>PRODUCT_STATUS_CREATE));
			$info['reset_time']=time();
			$this->msg_ok($info,'更新完成');
		}
		exit;
	}
	
	//生产板进度编辑
	function product_update(){
		$order_id=isset($_GET['order_id'])?intval($_GET['order_id']):0;
		//$btn=!empty($_GET['btn'])?$_GET['btn']:'';
		$user=$this->visitor->get();
		$result=array();
		if (!$order_id){
			$result['msg']="没有搜索到该订单";
			$result['flag']=false;
			exit(json_encode($result));
		}
// 		if (!$btn){
// 			$result['msg']="非法操作1";
// 			$result['flag']=false;
// 			exit(json_encode($result));
// 		}
		if (IS_POST){
			$data=array();
			$btn=!empty($_POST['p_btn'])?$_POST['p_btn']:'';
			if (!$btn){
				$result['msg']="非法操作";
				$result['flag']=false;
				exit(json_encode($result));
			}
			if ($btn=="安排工厂"){
				if (in_array($user['role'], array(USER_MERCHANDISER,USER_MERCHANDISER_ADMIN,USER_MANAGER))){
					$data['product_status']=PRODUCT_STATUS_SEND_FACTORY;
					$data['product_date']=gmtime();
				}
			}elseif ($btn=="工厂提交"){
				if (in_array($user['role'], array(USER_FACTORY))){
					$data['product_status']=PRODUCT_STATUS_FACTORY_SUBMIT;
				}
			}elseif ($btn=="确认"){
				if (in_array($user['role'], array(USER_MERCHANDISER,USER_MERCHANDISER_ADMIN,USER_MANAGER))){
					$data['product_status']=PRODUCT_STATUS_CREATE;
				}
			}else{
				$result['msg']="非法操作";
				$result['flag']=false;
				exit(json_encode($result));
			}
			if (in_array($user['role'], array(USER_MERCHANDISER,USER_MERCHANDISER_ADMIN,USER_MANAGER,USER_FACTORY))){
				if (in_array($user['role'], array(USER_MERCHANDISER,USER_MERCHANDISER_ADMIN,USER_MANAGER))){
					$product_times=isset($_POST['product_times'])?$_POST['product_times']:0;
					if (!$product_times){
						$result['msg']="请选择第几板";
						$result['flag']=false;
						exit(json_encode($result));
					}
					$data['product_times']=$product_times;
				}
				$this->_order_mod->edit($order_id,$data);
				if ($this->_order_mod->has_error()){
					$this->show_warning($this->_order_mod->get_error());
					return;
				}
			}else{
				$result['msg']="没有权限操作";
				$result['flag']=false;
				exit(json_encode($result));
			}
			$result['msg']="操作成功";
			$result['flag']=true;
			$result['url']="index.php?app=order&act=edit&id=".$order_id;
			exit(json_encode($result));
		}
	}
	
	
	//检查工厂做货量是否超标
	function check_order_goods_num(){
		$factory_id = isset($_GET['factory_id']) ? intval($_GET['factory_id']) : 0;
		$year=isset($_GET['year']) ? intval($_GET['year']) : 0;
		$month=isset($_GET['month']) ? intval($_GET['month']) : 0;
		$result=array();
		if (!$factory_id){
			$result['flag']=false;
			$result['msg']="请选择工厂";
			exit(json_encode($result));
		}
		$factory_mod=&m('factory_info');
		$factory_info=$factory_mod->get($factory_id);
		if (empty($factory_info)){
			$result['flag']=false;
			$result['msg']="工厂无效";
			exit(json_encode($result));
		}
		$orders = $this->_order_mod->find(array(
				'conditions' => 'factory_id = ' . $factory_id.' AND status not '.db_create_in(array(ORDER_STATUS_CONFIRM,ORDER_STATUS_NO_CANCEL,ORDER_STATUS_SHIPPED)). ' AND order_create_date >= ' . strtotime($year . '-1-1') . ' AND order_create_date <= ' . strtotime($year . '-12-31')
		));
		$quantity = array(1=>0,2=>0,3=>0,4=>0,5=>0,6=>0,7=>0,8=>0,9=>0,10=>0,11=>0,12=>0);
		foreach ($orders as $k => $v) {
			switch (intval(date('m', $v['order_create_date']))) {
				case 1 :
					$quantity[1] += $v['quantity'];
					break;
				case 2 :
					$quantity[2] += $v['quantity'];
					break;
				case 3 :
					$quantity[3] += $v['quantity'];
					break;
				case 4 :
					$quantity[4] += $v['quantity'];
					break;
				case 5 :
					$quantity[5] += $v['quantity'];
					break;
				case 6 :
					$quantity[6] += $v['quantity'];
					break;
				case 7 :
					$quantity[7] += $v['quantity'];
					break;
				case 8 :
					$quantity[8] += $v['quantity'];
					break;
				case 9 :
					$quantity[9] += $v['quantity'];
					break;
				case 10 :
					$quantity[10] += $v['quantity'];
					break;
				case 11 :
					$quantity[11] += $v['quantity'];
					break;
				case 12 :
					$quantity[12] += $v['quantity'];
					break;
			}
		}
		$local_quantity=$quantity[$month];
		if ($month==12){
			$goods_num=0;
			$new_orders = $this->_order_mod->find(array(
					'conditions' => 'factory_id = ' . $factory_id.' AND status not '.db_create_in(array(ORDER_STATUS_CONFIRM,ORDER_STATUS_NO_CANCEL,ORDER_STATUS_SHIPPED)). ' AND order_create_date >= ' . strtotime($year+1 . '-1-1') . ' AND order_create_date <= ' . strtotime($year+1 . '-1-31')
			));
			$quantity = array(1=>0);
			foreach ($new_orders as $k => $v) {
				switch (intval(date('m', $v['order_create_date']))) {
					case 1 :
						$quantity[1] += $v['quantity'];
						break;
				}
			}
		}else{
			$goods_num=$month;
		}
		$new_num=$goods_num+1;
		$result['flag']=true;
		$str="该工厂的月生产量：".$factory_info['factory_goods_num']."\n".$month."月接单量:".$local_quantity."\n".$new_num."月接单量:".$quantity[$new_num];
		$result['msg']=$str;
		exit(json_encode($result));
	}
	
	
	//分派用户订单模块
	function batch_edit(){
		$user_info=$this->visitor->get();
		$member_mod=&m('member');
		$order_id=isset($_GET['id'])?$_GET['id']:0;
		if (($user_info['role']==USER_MERCHANDISER && $user_info['role_cate']==ROLE_MERCH) || $user_info['role']==USER_MANAGER){
			if (!$order_id){
				$this->show_warning('order_not_exist');
				return;
			}
			if (!IS_POST){
				$conditions="activation=1 and role=".USER_CLIENT;
				$country_list=$member_mod->get_consumer_country($conditions,'mem.user_id');
				if (!empty($country_list)){
					foreach ($country_list as $key=>$rows){
						$countrys=$rows['country'];
						$country_info=$member_mod->find(array(
								'join'=>'has_consumer',
								'fields'=>'user_name,member.user_id',
								'conditions'=>"activation=1 and role=".USER_CLIENT." and country='".$countrys."'"
						));
						$country_list[$key]['user_list']=$country_info;
					}
				}
				$this->assign('country_list',$country_list);
				$this->display('sample.batch.html');
			}else{
				$data=array();
				$consumer_arr_id=isset($_POST['consumer_arr_id'])?$_POST['consumer_arr_id']:0;
				if (empty($consumer_arr_id)){
					$this->show_message('没有数据提交');
					exit;
				}
				$consumer_arr=implode(',', $consumer_arr_id);
				$data['consumer_arr_id']=$consumer_arr;
				$this->_order_mod->edit("order_id in ($order_id)",$data);
				if ($this->_order_mod->has_error()){
					$this->show_warning($this->_order_mod->get_error());
					return;
				}
				$this->show_message('分派客户模板成功');
			}
		}else{
			$this->show_warning('no_powers_to_visit');
			return;
		}
	}
	
	
	//取消全部的模板分配
	function batch_cancel(){
		$user_info=$this->visitor->get();
		if (($user_info['role']==USER_MERCHANDISER && $user_info['role_cate']==ROLE_MERCH) || $user_info['role']==USER_MANAGER){
			//$merch_id=$user_info['user_id'];
			$this->_order_mod->edit('1=1',array('consumer_arr_id'=>null));
			if ($this->_order_mod->has_error()){
				$this->show_warning($this->_order_mod->get_error());
				return;
			}
			$this->show_message('取消全部分派客户模板成功');
		}else{
			$this->show_warning('no_powers_to_visit');
			return;
		}
	}
	
	
	//取消全部的展示样板
	function reveal_cancel(){
		$user_info=$this->visitor->get();
		if (($user_info['role']==USER_MERCHANDISER && $user_info['role_cate']==ROLE_MERCH) || $user_info['role']==USER_MANAGER){
			//$merch_id=$user_info['user_id'];
			$this->_order_mod->edit('is_preset=1',array('is_preset'=>0));
			if ($this->_order_mod->has_error()){
				$this->show_warning($this->_order_mod->get_error());
				return;
			}
			$this->show_message('取消全部默认展示订单成功');
		}else{
			$this->show_warning('no_powers_to_visit');
			return;
		}
	}
	
	
	//系统分配展示模板给用户
	function assign_sys_order(){
		$user_info=$this->visitor->get();
		$order_id=isset($_GET['id'])?$_GET['id']:0;
		if (($user_info['role']==USER_MERCHANDISER && $user_info['role_cate']==ROLE_MERCH) || $user_info['role']==USER_MANAGER){
			if (!$order_id){
				$this->show_warning('order_not_exist');
				return;
			}
			if (!IS_POST){
				$this->display('sample.sys_assign.html');
			}else{
				$data=array();
				$is_preset=isset($_POST['is_preset'])?$_POST['is_preset']:0;
				$data['is_preset']=$is_preset;
				$this->_order_mod->edit("order_id in ($order_id)",$data);
				if ($this->_order_mod->has_error()){
					$this->show_warning($this->_order_mod->get_error());
					return;
				}
				$this->show_message('分派系统展示模板成功');
			}
		}else{
			$this->show_warning('no_powers_to_visit');
			return;
		}
	}
	
	
	//设为默认图片
	function default_image(){
		$id = empty($_GET['id']) ? 0 : intval($_GET['id']);
		$order_id = empty($_GET['order_id']) ? 0 : intval($_GET['order_id']);
		$result=array();
		if (!$id && !$order_id) {
			if ($_GET['ajax']) {
				$result=array('done'=>'false','msg'=>Lang::get('file_not_exist'));
				exit(ecm_json_encode($result));
			}
			return;
		}
	
		$upload_mod =& m('upload');
		$file = $upload_mod->get_info($id);
		if (empty($file)) {
			if ($_GET['ajax']) {
				$result=array('done'=>'false','msg'=>Lang::get('file_not_exist'));
				exit(ecm_json_encode($result));
			}
			return;
		}
	
		if (!$this->_order_mod->edit($order_id,array('default_image'=>$file['file_path']))) {
			if ($_GET['ajax']) {
				$result=array('done'=>'false','msg'=>Lang::get('setting_error'));
				exit(ecm_json_encode($result));
			}
			return;
		}
		if ($_GET['ajax']) {
			$result=array('done'=>'true','msg'=>Lang::get('setting_success'));
		}
		exit(ecm_json_encode($result));
	}
	
	
	function cancel_user_assign(){
		$uid=isset($_GET['uid'])?$_GET['uid']:0;
		$id=isset($_GET['id'])?$_GET['id']:'';
		if(!$id && !$uid){
			$this->show_warning("参数不对");
			return;
		}
		$ids=explode(',', $id);
		$order_list=$this->_order_mod->find(array(
			'conditions'=>'order_id'.db_create_in($ids),
			'fields'=>'consumer_arr_id,buyer_id'	
		));
		if(!empty($order_list)){
			foreach($order_list as $key=>$val){
				$consumer_arr_id=explode(',', $val['consumer_arr_id']);
				if (in_array($uid, $consumer_arr_id)){
					unset($consumer_arr_id[array_search($uid , $consumer_arr_id)]);
				}
				$this->_order_mod->edit($val['order_id'],array('consumer_arr_id'=>implode(',', $consumer_arr_id)));
				if ($this->_order_mod->has_error()){
					$this->show_warning($this->_order_mod->get_error());
					return;
				}
			}
		}
		$this->show_message("取消用户展示成功");
	}
	
	//上传细节图
	function upload_thumb(){
		$order_id=isset($_GET['order_id'])?intval($_GET['order_id']):0;
		if (!$order_id){
			$this->show_warning("订单不存在");
			return;
		}
		$user_info=$this->visitor->get();
		if(in_array($user_info['role'], array(USER_CLIENT,USER_FACTORY))){
			$this->show_warning('no_powers_to_visit');
			return;
		}else{
			$order=$this->_order_mod->get($order_id);
			if (empty($order)){
				$this->show_warning("订单不存在");
				return;
			}
			//细节图
			$file_mod=&m('upload');
			$order['consumer_order_thumb'] = $file_mod->find(array(
					'conditions' => 'file_type = ' . BELONGS_ORDER_THUMB_IMG . ' AND key_id = ' . $order_id,
					'order' => 'file_id ASC',
			));
			$this->assign('belongs_order_thumb',BELONGS_ORDER_THUMB_IMG);
			$this->assign('order',$order);
			$this->display('order.thumb.html');
		}
	}
	
	
	//大货折扣页面
	function order_discount(){
		$order_id=isset($_GET['id'])?$_GET['id']:0;
		$user=$this->visitor->get();
		if (!$order_id){
			$this->show_warning("该订单不存在");
			return;
		}
		$order_info=$this->_order_mod->get($order_id);
		if (empty($order_info)){
			$this->show_warning("该订单不存在");
			return;
		}
		if (!IS_POST){
			$file_mod=&m('upload');
			/* 折扣原因附件 */
			$this->assign('file_disreason', $file_mod->find(array('conditions'=>'file_type = '.BELONGS_ORDER_DIS_REASON.' AND key_id = '.$order_id,'order'=>'file_id ASC')));
			$this->assign('belongs_disreason', BELONGS_ORDER_DIS_REASON);
			$disreason_type_mod =& m('disreason_type');
			$this->assign('disreason_type_list', $disreason_type_mod->find(array('conditions'=>"1=1")));
			$this->assign('order',$order_info);
			$this->display('order.discount.html');
		}else{
			$submit_val=isset($_POST["submit"])?trim($_POST["submit"]):"";
			$dis_data=array();
			$dis_form_data=array(
					"dis_reason_type"=>isset($_POST["dis"]["dis_reason_type"])?trim($_POST["dis"]["dis_reason_type"]):"",
					"dis_money"=>isset($_POST["dis"]["dis_money"])?floatval($_POST["dis"]["dis_money"]):"",
					"dis_reason"=>isset($_POST["dis"]["dis_reason"])?trim($_POST["dis"]["dis_reason"]):""
			);
				
			if($order_info['dis_status']==ORDER_DIS_STATUS_NO)
			{
				$dis_data=$dis_form_data;
				if($submit_val=="送财务审批" && ($user['role']==USER_MERCHANDISER|| $user['role']==USER_MANAGER))
				{
					$dis_data["dis_status"]=ORDER_DIS_STATUS_APPROVE_FINANCE;
				}
			}elseif($order_info['dis_status']==ORDER_DIS_STATUS_APPROVE_FINANCE)
			{
				if($submit_val=="审批通过" && $user['role']==USER_FINANCE)
				{
					$dis_data["dis_status"]=ORDER_DIS_STATUS_SEND_FACTORY;
				}else{
					if(in_array($user['role'], array(USER_FINANCE)))
					{
						$dis_data=$dis_form_data;
					}
				}
				if(in_array($user['role'], array(USER_MANAGER,USER_MERCHANDISER)))
				{
					$dis_data=$dis_form_data;
				}
				
			}elseif ($order_info['dis_status']==ORDER_DIS_STATUS_SEND_FACTORY){
				if ($submit_val=="确认" && $user['role']==USER_FACTORY){
					$dis_data["dis_status"]=ORDER_DIS_STATUS_FACTORY_CONFIRM;
					$dis_data["goods_discount"]=$order_info['dis_money'];
					$ship_amount=floatval($order_info['dealwith_amount'])-floatval($order_info['dis_money']);
					$dis_data["ship_amount"]=$ship_amount;
					$dis_data["dis_isreturn"]=isset($_POST["dis"]["dis_isreturn"])?intval($_POST["dis"]["dis_isreturn"]):0;
				}
			}
			
			if($submit_val=="重置" && in_array($user['role'], array(USER_MANAGER,USER_FINANCE)))
			{
				$dis_data["dis_status"]=ORDER_DIS_STATUS_APPROVE_FINANCE;
			}
			$this->_order_mod->edit($order_id,$dis_data );
			if ($this->_order_mod->get_error()) {
				$this->show_warning($this->_order_mod->get_error());
				return;
			}
			
			//状态变动时发送邮件和写记录
			$new_order_info=$this->_order_mod->get($order_id);
			$new_order_info['dis_isreturn']=empty($new_order_info['dis_isreturn'])?"否":"是";
			$mod_pro_records=&m("pro_records");
			$pro_data=array(
					"type"=>PRO_RECORDS_ORDER,
					"key_id"=>$order_id,
					"rec_name"=>$this->visitor->get("user_name"),
					"rec_time"=>gmtime()
			);
			if($order_info['dis_status']==ORDER_DIS_STATUS_APPROVE_FINANCE && $new_order_info['dis_status']==ORDER_DIS_STATUS_SEND_FACTORY)
			{
				$this->_send_mail_on_disreason_send_factory($new_order_info);
				$pro_data["rec_buff"]="提交大货折扣并送工厂";
					
			}
			elseif($order_info['dis_status']==ORDER_DIS_STATUS_SEND_FACTORY&&$new_order_info['dis_status']==ORDER_DIS_STATUS_FACTORY_CONFIRM )
			{
				$this->_send_mail_on_disreason_factory_confirm($new_order_info);
				$pro_data["rec_buff"]="工厂已确认大货折扣";
		
			}elseif($order_info['dis_status']==ORDER_DIS_STATUS_NO && $new_order_info['dis_status']==ORDER_DIS_STATUS_APPROVE_FINANCE)
			{
				$pro_data["rec_buff"]="送财务审批大货折扣";
					
			}
			if($submit_val=="重置" && in_array($user['role'], array(USER_MANAGER,USER_FINANCE)))
			{
				$pro_data["rec_buff"]="重置大货折扣";
			}
			if(!$mod_pro_records->add($pro_data))
			{
				$this->show_warning($mod_pro_records->get_error());
			}
			header("location:index.php?app=order&act=order_discount&id={$order_id}");
		}
	}
	
	
	//同款比价
	function same_style(){
		$fabric_mod=&m('fabric_info');
		$colorcard_mod=&m('color_card');
		$conditions=$this->_get_query_conditions(array(
			array(
				'field' => 'style_id',
				'equal' => '=',
				'name'	 => 'style_id'
			),
			array(
					'field' => 'brand_id',
					'equal' => '=',
					'name'	 => 'brand_id'
			),
			array(
					'field' => 'buyer_id',
					'equal' => '=',
					'name'	 => 'buyer_id'
			),
			array(
					'field' => 'factory_id',
					'equal' => '=',
					'name'	 => 'factory_id'
			)
		));
		$style_mod =& m('style');
		$this->assign('style_list', $style_mod->find(array('conditions'=>'if_show = 1', 'order'=>'style_name ASC')));
		
		$buyer_mod=&m('member');
		$buyers=$buyer_mod->find(array('conditions'=>'activation=1 and role='.USER_CLIENT));
		$this->assign('buyer_list',$buyers);
		
		$factory_mod=&m('factory_info');
		$this->assign('factory_list',$factory_mod->find(array('fields'=>'factory_info.factory_id,factory_info.factory_name','conditions'=>'activation=1','join'=>'belongs_factory_member')));
		$brand_mod=&m('brand');
		$brand_list = $brand_mod->find(array(
				'conditions' => 'if_show = 1',
				'join'=>"belong_company",
				'order' => 'brand_name ASC'
		));
		$this->assign('brand_list',$brand_list);
		//显示已确认的所有订单
		$conditions .=" and status".db_create_in(array(ORDER_STATUS_CONFIRM,ORDER_STATUS_SHIPPED));
		$page = $this->_get_page();
		$order = empty($_GET['order']) ? 'order_create_date DESC' : str_replace('-', ' ', trim($_GET['order']));
		if ($order != 'order_create_date DESC' || $order != 'order_create_date ASC') {
			$order .= ', order_create_date DESC';
		}
        $orders=$this->_order_mod->find(
                array(
                	'conditions'=>'1=1'.$conditions,
                    'count' => true,
                    'limit' => $page['limit'],
					'order' => $order
                )
        );
        if (!empty($orders)){
        	$ss_mod=&m('ss');
        	foreach ($orders as $key=>$rows){
        		$order_id=$rows['order_id'];
        		$ss_info=$ss_mod->get(array('conditions'=>'order_id='.$order_id));
        		if (!empty($ss_info)){
        			$fabric_info=$fabric_mod->find(array(
        					'join'=>'belongs_fabric_shop',
        					'fields'=>'*,fabric_info.description',
        					'conditions'=>'ss_id='.$ss_info['ss_id'].' and cc_id!=0'
        			));
        		}
        		if (!empty($fabric_info)){
        			foreach ($fabric_info as $k=>$v){
        				$cc_id=$v['cc_id'];
        				$cc_info=$colorcard_mod->get($cc_id);
        				$fabric_info[$k]['color_img']=$cc_info['default_image'];
        			}
        		}
        		$orders[$key]['order_fabric']=$fabric_info;
        	}
        }
        $page['item_count'] = $this->_order_mod->getCount();
        $this->_format_page($page);
        $this->assign('page_info', $page);
        $this->assign('order_list',$orders);
		$this->display('order.same_style.html');
	}
	
	
	//推荐色卡查看
	function recomm_view(){
		$order_id=!empty($_GET['order_id'])?$_GET['order_id']:0;
		if (!$order_id){
			$this->show_warning('order_not_exist');
			return;
		}
		$order_mod=&m('order');
		$colorcard_mod=&m('color_card');
		$order=$order_mod->get_info($order_id);
		if ($order['recomm_cc_id']){
			$recomms=$colorcard_mod->find(array(
				'conditions' => 'cc_id '.db_create_in($order['recomm_cc_id']),
				'order' => 'cc_id ASC',	
				'fields'=>'default_image'
			));
		}
		$this->assign('recomm_img',$recomms);
		$this->assign('order_id',$order_id);
		$this->assign('user',$this->visitor->get());
		$this->display('sample.recomm_color.html');
	}
	
	
	//移除推荐色卡
	function remove(){
		$cc_id = !empty($_GET['cc_id'])?$_GET['cc_id']:0;
		$order_id=!empty($_GET['order_id'])?$_GET['order_id']:0;
		if (!$order_id){
			$this->show_warning('order_not_exist');
			return;
		}
		if(!$cc_id){
			$this->show_warning('color_not_exist');
			return;
		}
		$order_mod=&m('order');
		$order=$order_mod->get_info($order_id);
		if ($order['recomm_cc_id']){
			$recomm_id=explode(',', $order['recomm_cc_id']);
			foreach ($recomm_id as $k=>$v){
				if ($v==$cc_id){
					unset($recomm_id[$k]);
				}
			}
			$recomm_arr_id=implode(',', array_filter($recomm_id));
			$order_mod->edit($order_id,array('recomm_cc_id'=>$recomm_arr_id));
			if ($order_mod->has_error()){
				$this->show_warning($order_mod->get_error());
				return;
			}
		}
		$this->show_message("remove_success");
	}
	
	
	//已付款
	function pay_money(){
		$id=!empty($_GET['id'])?$_GET['id']:0;
		if ($this->visitor->get('role')!=USER_FINANCE){
			$this->show_warning('no_powers_to_visit');
			return;
		}
		if (!$id){
			$this->show_warning('操作错误,请重新选择');
			return;
		}
		$this->_order_mod->edit('order_id'.db_create_in(array($id)),array('status'=>ORDER_STATUS_PAY_MONEY));
		if ($this->_order_mod->has_error()){
			$this->show_warning($this->_order_mod->get_error());
			return;
		}
		$this->show_message('已付款成功');
	}
}
?>
